<?php 
/**
 * Roster audit controller is for warehouse to check and calcualte the 
 * payroll roster relate issue 
 * most the funcon is already in the landing page of control panel 
 * roster audit contain the following section
 * 1. payroll wizard 
 * 2. case create and managerment 
 * 3. Roster and attendance checking 
 * 4. Unconfirm Roster functons
 * 
 * 
 */
class RosterauditController extends Zend_Controller_Action
{

	protected static $arrShopMaping;
	
    public function init(){
    /**
	 *
	 *
	 */    
	self::$arrShopMaping = unserialize(ARR_APOS_NEW_SHOP_MAPPING);
	}

    public function indexAction(){
	
	}
	/**
	 * this also be consider the control panel of account department 
	 */
	public function controlPanelAction(){
		
		
	}
	
	/**
	 * this function is for manager to create case 
	 * manager may crate case in following conditions
	 * 1.missing attendance record
	 * 2. attendance reocrd does not matching the roster 
	 * stand alone case has been disabled
	 * create case is only available in manager listing problems 
	 */
	public function createCaseAction(){
		
		$preLoad = "";
		if($_POST){
		
			//$post Data from Listing Problem 
			$preLoad =unserialize(base64_decode($_POST["case"]));	
		}
		else{
					
			$this->view->idMgr = base64_decode(trim($this->_getParam("token")));
		}

		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$this->view->stList = $stDetail->listStaffByNickName();
		
		$this->view->preLoad = $preLoad;
	}
	
	/**
	 * this is the second step of create case 
	 * after case is filled , it give the manger final calculated hours to double check
	 * if everything is set , then submit the case 
	 */
	public function confirmCreateCaseAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		
		$cPath = getcwd();
		$uploadPathOn = '/upload/onduty/';
		$uploadPathOff = '/upload/offduty/';
		
		$willPayHour = 0;
		$needPayHour = 0;
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$ts = new Model_DbTable_Roster_Timesheet();
		
		if($_POST){
			
			$caseIdCase = $_POST['case_id'];
			
			$stLine = $stDetail->getDetail($_POST['staff_name']);
			$this->view->stName = $stLine['ni'].' ('.ucwords(Model_EncryptHelper::getSslPassword($stLine['n'])).')';
			$manShiftBeginHour = $_POST['man_shift_begin_hour'];
			$manShiftBeginMin = $_POST['man_shift_begin_min'];
			$manShiftEndHour = $_POST['man_shift_end_hour'];
			$manShiftEndMin = $_POST['man_shift_end_min'];
				
			$staffShiftBeginHour = $_POST['act_shift_begin_hour'];
			$staffShiftBeginMin = $_POST['act_shift_begin_min'];
			$staffShiftEndHour = $_POST['act_shift_end_hour'];
			$staffShiftEndMin = $_POST['act_shift_end_min'];
				
				
			$staffProposeBeginHour = $_POST['pro_shift_begin_hour'];
			$staffProposeBeginMin = $_POST['pro_shift_begin_min'];
			$staffProposeEndHour = $_POST['pro_shift_end_hour'];
			$staffProposeEndMin = $_POST['pro_shift_end_min'];
			
			// detect if the propose hour Overlaping in any other confirmed roster in other shop 
			
			$strShiftBegin = $_POST['shift_date'].' '.$_POST['pro_shift_begin_hour'].':'.$_POST['pro_shift_begin_min'].':00';
			$strShiftEnd =  $_POST['shift_date'].' '.$_POST['pro_shift_end_hour'].':'.$_POST['pro_shift_end_min'].':00';
			
			//$ts->ifTimeSheetOverlaped($idStaff, $shop, $intShiftBegtin, $intShiftEnd);
			
			
			
			$breakFirstMin =$_POST['first_break'];
			$breakSecondMin = $_POST['second_break'];
				
			if($staffShiftBeginHour =='-' || $staffShiftBeginMin =='-'  || $staffShiftEndHour =='-' || $staffShiftEndMin =='-' ){
			
				$willPayHour = 0;
			}
			else{
			
				// calculate will pay
				$shiftPayhour = round(($manShiftEndHour - $manShiftBeginHour) + ($manShiftEndMin - $manShiftBeginMin) / 60,2);
				$actualBreak = 0.5;
			
				if($shiftPayhour < 5 ){
						
					$actualBreak = round(($breakFirstMin + $breakSecondMin) / 60,2);
				}
			
				if($shiftPayhour >= 5 ){
						
					$actualBreak = (round(($breakFirstMin + $breakSecondMin) / 60,2) > 0.5)?round(($breakFirstMin + $breakSecondMin) / 60,2):0.5;
				}
			
				if($shiftPayhour >= 9 ){
						
					$actualBreak = (round(($breakFirstMin + $breakSecondMin) / 60,2) > 1)?round(($breakFirstMin + $breakSecondMin) / 60,2):1;
				}
			
				// find difference.compare shift begin
				$beginDiff = round(($staffShiftBeginHour*60 + $staffShiftBeginMin - ($manShiftBeginHour*60 + $manShiftBeginMin)) /60 ,2);
			
				$beginDiff = ($beginDiff >0)?$beginDiff:0;
			
				$endDiff = round(($manShiftEndHour*60 + $manShiftEndMin - ($staffShiftEndHour*60 + $staffShiftEndMin)) / 60 ,2);
			
				$endDiff = ($endDiff >0)?$endDiff:0;
			
				$willPayHour = $shiftPayhour - $actualBreak - $beginDiff - $endDiff;
			
			
			}
				
			// need pay
				
			$needPayHour = round(($staffProposeEndHour*60 + $staffProposeEndMin - $staffProposeBeginHour*60 - $staffProposeBeginMin )/60,2);
				
			$needPayBreak = 0.5;
				
			if($needPayHour <5){
				$needPayBreak = 0;
			}
				
			if($needPayHour >=5){
				$needPayBreak = 0.5;
			}
			if($needPayHour >=9){
				$needPayBreak = 1;
			}
				
			if($actualBreak >$needPayBreak) {
				$needPayBreak = $actualBreak;
			}
				
			$needPayHour = $needPayHour - $needPayBreak;

			
		// upload file 

			//upload file
			$linkImageOpen = 0;
			$linkImageClose = 0;
			
				
			if(isset($_FILES['footage_on_duty'])){
				$onDutyFileName = $_FILES['footage_on_duty']['name'];
				$ext = pathinfo($onDutyFileName, PATHINFO_EXTENSION);
				$newFileName = $caseIdCase."_on.".$ext;
					
					
				if(move_uploaded_file($_FILES['footage_on_duty']['tmp_name'],$cPath.$uploadPathOn.$newFileName)){
			
					$linkImageOpen = $uploadPathOn.$newFileName;
				}
			}
			
			if(isset($_FILES['footage_off_duty'])){
				$offDutyFileName = $_FILES['footage_off_duty']['name'];
				$ext = pathinfo($offDutyFileName, PATHINFO_EXTENSION);
				$newFileName = $caseIdCase."_off.".$ext;
					
					
				if(move_uploaded_file($_FILES['footage_off_duty']['tmp_name'],$cPath.$uploadPathOff.$newFileName)){
						
					$linkImageClose = $uploadPathOff.$newFileName;
				}
			}
			
			$this->view->imgOpen = $linkImageOpen;
			$this->view->imgClose = $linkImageClose;
			$this->view->willPayHour = $willPayHour;
			$this->view->needPayHour = $needPayHour;
			$hourDiff = $needPayHour - $willPayHour;
			$this->view->hourDiff = $hourDiff;
			
		}// end post 
		
	}
	
	/**
	 * this  is the final step of create case 
	 * this is the actual page to save the case and init the case management 
	 * after this step , manager can see this case in case management 
	 */
	public function saveAttnCaseAction(){
		
		$attCase = new Model_DbTable_Roster_Attncase();
		$acRecord = new Model_DbTable_Roster_Attcaserecord();
		
		$willPayHour = 0;
		$needPayHour = 0;
		
		
		
		if($_POST){
			
			$caseIdCase = $_POST['case_id'];
			$idManager = $_POST['id_manager'];
			$idStaff = $_POST['staff_name'];
			
			$shopCode = $_POST['shop_code'];
			
			$shiftDate = $_POST['shift_date'];
			
			//$manShiftBeginHour = $_POST['man_shift_begin_hour'];
			//$manShiftBeginMin = $_POST['man_shift_begin_min'];
			//$manShiftEndHour = $_POST['man_shift_end_hour'];
			//$manShiftEndMin = $_POST['man_shift_end_min'];
			
			$staffShiftBeginHour = 0;
			$staffShiftBeginMin = 0;//$_POST['act_shift_begin_min'];
			$staffShiftEndHour = 0;//$_POST['act_shift_end_hour'];
			$staffShiftEndMin = 0;//$_POST['act_shift_end_min'];
			
			
			$staffProposeBeginHour = $_POST['pro_shift_begin_hour'];
			$staffProposeBeginMin = $_POST['pro_shift_begin_min'];
			$staffProposeEndHour = $_POST['pro_shift_end_hour'];
			$staffProposeEndMin = $_POST['pro_shift_end_min'];
			
			
			
			$breakFirstMin =$_POST['first_break'];
			$breakSecondMin = $_POST['second_break'];
			
			 
			//upload file 
			$linkImageOpen = $_POST['link_img_open'];
			$linkImageClose = $_POST['link_img_close'];

			

			$offlineInvOn = $_POST['apos_invoice_on_duty'];
			$offlineInvOff = $_POST['apos_invoice_off_duty'];

			$reasonComment = $_POST['reason_missing_footage'];
			$detailExplain = $_POST['detail_explain'];

			$hourRequest = $_POST['need_pay_hour'];
			$hourAllocate = $_POST['will_pay_hour'];
			
			$lodgeDate = Model_DatetimeHelper::dateToday();
			
			if($idManager >0){
			$idCase = 	$attCase->addAttncase($caseIdCase, $idManager, $idStaff, $shopCode, $shiftDate, $staffProposeBeginHour, $staffProposeBeginMin, $staffProposeEndHour, 
						$staffProposeEndMin, $staffShiftBeginHour, $staffShiftBeginMin, $staffShiftEndHour, $staffShiftEndMin, $breakFirstMin,
				    	 $breakSecondMin, $linkImageOpen, $linkImageClose, $offlineInvOn, $offlineInvOff, $reasonComment, $detailExplain, $hourRequest, $hourAllocate, $lodgeDate);
			
			
			 $acRecord->addAttcaserecord($idCase,1,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$idManager);
			}else{
				
				echo "<h1>ERROR OCCUR, CASE NOT CREATED</h1>";
				
			}
		}
	}
	
	/**
	 * check roster by name is actuall check attendance by name 
	 * it missing the Arrange Roster and manager confirmed roster part
	 * it show the name list 
	 * it show if the staff has leave 
	 * it show the entry point of the staff info page 
	 * it show the staff working shops
	 * it show the staff working time from date to date 
	 */
	public function checkRosterByNameAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		
		$initial = 1;
		$initial = $this->_getParam("i");
		$staffId = $this->_getParam("std");
		
		$su = $this->_getParam("su");
		
		$this->view->issu = false;
		if($su=="unlimiteds"){
			
			$this->view->issu = true;
			
		}
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$dateBegin = $dateEnd = $dateToday;
		
		if(isset($_POST["date_begin"])){
			$dateBegin = $_POST["date_begin"];
		}
		if(isset($_POST["date_end"])){
			$dateEnd = $_POST["date_end"];
		}		
		
		$this->view->showSlist = false;
		$this->view->showDetail = false;
		$this->view->sList = "";
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$ts = new Model_DbTable_Roster_Timesheet();
		
		
		if($this->_getParam("i")!=""){
			
			$this->view->showSlist = true; 
			$this->view->sList = $stDetail->listStaffByLastName($initial);
			$this->view->showDetail = false;
		}
		
		if($this->_getParam("std")!=""){
			
			$arrRlist = array();// result List
			
			$this->view->idStaff = $staffId;
			  
			$this->view->showSlist = false; // wait decide
			$nameRow = $stDetail->getDetail($staffId);
			$this->view->staffName =Model_EncryptHelper::getSslPassword($nameRow["n"]);
			$this->view->nickName = $nameRow['ni'];
			//$this->view->SList = $stDetail->listStaffByLastName($inital);
			
			//$rList = $attRecord->listRecordByStaffId($staffId,$dateBegin,$dateEnd);
			
			//$this->view->rList = $rList;
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
			
			foreach($arrDate as $v){
				//get how many shop the today

				$shifts = $ts->listShiftByStaffIdByDate($staffId, $v, $v);
				
				$sList = $attRecord->getShopHeadByStaffIdByDate($staffId, $v, $v);
				if(!$sList){
					if($shifts){
						foreach($shifts as $sk => $sv){
							$arrTmp= array();
							$arrTmp["date"] =$v;
							$arrTmp["day"]=date("D",strtotime($v));
							$arrTmp["shophead"] =$sv["shop_head"];
							if(!empty($sv['confirm_shift_begin'])){
								$arrTmp["shift_begin"]=$sv["confirm_shift_begin"];
								$arrTmp["shift_end"]=$sv["confirm_sheift_end"];
							}else{
								$arrTmp["shift_begin"]=$sv["shift_begin"];
								$arrTmp["shift_end"]=$sv["shift_end"];
							}
							$arrTmp["act_begin"]="";
							$arrTmp["act_end"]="";
							$arrTmp["fake_act_begin"]=false;
							$arrTmp["fake_act_end"]=false;
								if($sv['holiday_check'] == 1){
									$arrTmp["status_begin"]="holiday";
									$arrTmp["status_end"]="holiday";
								}else{
									$arrTmp["status_begin"]="-";
									$arrTmp["status_end"]="-";
								}
					
					
							$arrTmp["shift_normal_hour"] = "";
							$arrTmp["shift_6pm_hour"] = "";
							$arrTmp["shift_normal_hour"] = "";
							$arrTmp["shift_6pm_hour"] = "";
							$arrTmp["act_normal_hour"] = "";
							$arrTmp["act_6pm_hour"] = "";
							$arrTmp["act_sat_hour"] = "";
							$arrTmp["act_sun_hour"] = "";
							$arrTmp["offline_begin"]=false;
							$arrTmp["offline_end"]=false;
							$arrRlist[] = $arrTmp;
						}
					}else{
						$arrTmp= array();
						$arrTmp["date"] =$v;
						$arrTmp["day"]=date("D",strtotime($v));
						$arrTmp["shophead"] =" - ";
						$arrTmp["shift_begin"]="";
						$arrTmp["shift_end"]="";
						$arrTmp["act_begin"]="";
						$arrTmp["act_end"]="";
						$arrTmp["fake_act_begin"]=false;
						$arrTmp["fake_act_end"]=false;
						$arrTmp["status_begin"]="-";
						$arrTmp["status_end"]="-";
						$arrTmp["shift_normal_hour"] = "";
						$arrTmp["shift_6pm_hour"] = "";
						$arrTmp["shift_normal_hour"] = "";
						$arrTmp["shift_6pm_hour"] = "";
						$arrTmp["act_normal_hour"] = "";
						$arrTmp["act_6pm_hour"] = "";
						$arrTmp["act_sat_hour"] = "";
						$arrTmp["act_sun_hour"] = "";
						$arrTmp["offline_begin"]=false;
						$arrTmp["offline_end"]=false;
						$arrRlist[] = $arrTmp;						
						
					}
				}else{
					
				
					foreach($sList as $sh){
							
						$arrTmp= array();
						$arrTmp["date"] =$v;  //date
					
						$arrTmp["day"]=date("D",strtotime($v)); //day
						$intDay =date("N",strtotime($v));
						$arrTmp["shophead"] = Model_EncryptHelper::getSslPassword($sh["sh"]);//shop
						
						$shopLocation = 1;
							if($arrTmp["shophead"] =="ADPC" || $arrTmp["shophead"] =="CLPC" ||$arrTmp["shophead"] =="CLIC" ||$arrTmp["shophead"] =="WLIC" ){
								$shopLocation = 2;
							}
					
						$tList = $ts->listShiftByStaffIdByDateByShop($staffId,Model_EncryptHelper::getSslPassword($sh["sh"]),$v,$v);
							if($tList){
								if(!empty($tList['confirm_shift_begin'])){
									$arrTmp["shift_begin"] = $tList["confirm_shift_begin"];//time sheet start
									$arrTmp["shift_end"]=$tList["confirm_shift_end"];	//time sheet end	
								}else{
									$arrTmp["shift_begin"] = $tList["shift_begin"];//time sheet start
									$arrTmp["shift_end"]=$tList["shift_end"];	//time sheet end
								}				
							}else{
								$arrTmp["shift_begin"] = "";//time sheet start
								$arrTmp["shift_end"]= "";	//time sheet end						
							}
						$actList = $attRecord->getFirstOnLastOffDuty($staffId,$v,$sh["sh"]);
					
						$arrTmp["act_begin"]=$actList[0];//act start
						$arrTmp["act_end"]=$actList[1];//act end
						$arrTmp["fake_act_begin"] = $actList[2]; // manul inserted begin
						$arrTmp["fake_act_end"] = $actList[3]; // manul inserted end
						$arrTmp["offline_begin"]=$actList[4];
						$arrTmp["offline_end"]=$actList[5];
		
						//compare status

						$arrTmp["status_begin"] = $attRecord->compareStartTime($arrTmp["shift_begin"], $arrTmp["act_begin"]);
						$arrTmp["status_end"] = $attRecord->compareFinishTime($arrTmp["shift_end"], $arrTmp["act_end"]);
						if($tList['holiday_check'] == 1){
							$arrTmp["status_begin"] = 'holiday';
							$arrTmp["status_end"] = 'holiday';
						}
					
					
					//Shift
					if( $intDay<6){

						$arrShiftHour = $ts->calShiftHours($v, $arrTmp["shift_begin"], $arrTmp["shift_end"], $shopLocation);

						$arrTmp["shift_normal_hour"] = $arrShiftHour[0];
						$arrTmp["shift_6pm_hour"] = $arrShiftHour[1];
					}
					else{
						if($arrTmp["shift_begin"] == "" ||  $arrTmp["shift_end"]==""){	
							$arrTmp["shift_normal_hour"] = "";
							
						}
						else{
							$arrTmp["shift_normal_hour"] = round(($arrTmp["shift_end"]-$arrTmp["shift_begin"])/3600,2);
									
						}
						$arrTmp["shift_6pm_hour"] = "";
					}
					
					if($intDay<6){
						
						$arrActHour = $ts->calShiftHours($v, $arrTmp["act_begin"], $arrTmp["act_end"], $shopLocation);
						$arrTmp["act_normal_hour"] = $arrActHour[0];
						$arrTmp["act_6pm_hour"] = $arrActHour[1]; 
						$arrTmp["act_sat_hour"] = "";
						$arrTmp["act_sun_hour"] = "";
						
					}
					if($intDay == 6){
						
						$arrTmp["act_normal_hour"] = "";
						$arrTmp["act_6pm_hour"] = "";
						$arrTmp["act_sat_hour"] = ($arrTmp["act_begin"]=="" || $arrTmp["act_end"]=="")?"":round(($arrTmp["act_end"]-$arrTmp["act_begin"])/3600,2);
						$arrTmp["act_sun_hour"] = "";						
						
						
					}
					if($intDay == 7){
						$arrTmp["act_normal_hour"] = "";
						$arrTmp["act_6pm_hour"] = "";
						$arrTmp["act_sat_hour"] = "";
						$arrTmp["act_sun_hour"] = ($arrTmp["act_begin"]=="" || $arrTmp["act_end"]=="")?"":round(($arrTmp["act_end"]-$arrTmp["act_begin"])/3600,2);						
					}
					
					
					//act normal hour
					//after 6 pm hour
					//total saturday hour , No afer 6 pm hour 
					//total sunday hour , no after 6pm hour 
					
					
					$arrRlist[] = $arrTmp; 
				}
				
				}
				//
				
				//
			$this->view->rList = $arrRlist;
			
			//var_dump($arrRlist);
				
			}
			
			$this->view->staffId = $staffId;
			//$result = $attRecord->restructure($rList);
			$this->view->showDetail = true;	
			
			
		}
		
			
	}
	
	public function checkRosterByShopAction(){
		
	}
	
	/**
	 * This function for Simon change rate and notice accounting
	 * @auther Leo 
	 * Modified on 2015-01-23 by Norman , add Approved by Ken Mail
	 * ONLY OLGA Click the approval button, the Rate will change , before that , the Rate WILL NOT CHANGE 
	 */
	
	public function changeRateApplyAction(){
		$rate = new Model_DbTable_Roster_Staffrate();
		$stfInfo = new Model_DbTable_Roster_Staffinfo();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$mail = new Model_Emailshandler();
		$dateToday = Model_DatetimeHelper::dateToday();
		$stfId = $this->_getParam('id');
		$this->view->applyRate = $this->_getParam('applyrate');
		$type = unserialize(PAYROLL_TYPE);
		$check = $this->_getParam('check');
		$rateApp = $rate->listAllPending();
		$this->view->pending = $rateApp;
		if(isset($_POST['submit'])){
			
			$url = "/rosteraudit/change-rate-apply/id/".$_POST['staff_name'];
			$this->_redirect($url);
			
		}
		$this->view->stfId = $stfId;
		$this->view->check = $check;
		
		if(isset($_POST['add_record'])){
			$link = null;
			$link2 = "";
			if(move_uploaded_file($_FILES['file']['tmp_name'],getcwd().'/import/review/'.$_FILES['file']['name'])){	
				$link = "/import/review/".$_FILES['file']['name'];
				$link2 = "<a href=\"http://".WEB_IP."/import/review/{$_FILES['file']['name']}\" target=\"_blank\">HERE</a>";
			}
			$stf = $stfInfo->getStaffinfo($stfId);
			$stfD = $stfDetail->getDetail($stfId);
			$rate->addRateApplication($stfId, $stf['new_rate'], $stf['id_package'], $_POST['newRate'], $_POST['newRateType'], $dateToday, $_POST['date'],$_POST['comment'], $link);
			
			
			$url = "<a href=\"http://".WEB_IP."/rosteraudit/change-rate-approval\" target=\"_blank\">http://".WEB_IP."/rosteraudit/change-rate-approval</a>";
			$title = "Staff Rate Change Application";
			$str = "Staff ".$stf['first_name']." ".$stf['last_name']."(".$stfD['ni'].")"." Apply Rate from $".$stf['new_rate']." -> $".$_POST['newRate']
			."<br/>Type:".$type[$stf['id_package']][1]." -> ".$type[$_POST['newRateType']][1]."<br/>Effect Date:".$_POST['date']."<br/>"."Comment:".$_POST['comment']."<br/>"."Review Document:".$link2."<br/>"."Please use below link to approve"."<br/>".$url."<br/> This Change Has Been Approved By Ken ";
			$mail->sendActionEmail('admin@phonecollection.com.au;payroll@phonecollection.com.au', $title, $str); // send to OLGA

						
			$str2 = "Staff ".$stf['first_name']." ".$stf['last_name']."(".$stfD['ni'].")"." Apply Rate from $".$stf['new_rate']." -> $".$_POST['newRate']
			."<br/>Type:".$type[$stf['id_package']][1]." -> ".$type[$_POST['newRateType']][1]."<br/>Effect Date:".$_POST['date']."<br/>"."Comment:".$_POST['comment']."<br/>"."Review Document:".$link2."<br/>";

			
			$url = "/rosteraudit/change-rate-apply/check/ok";
			$this->_redirect($url);
			
			$this->view->message = $str2;
		}
		
	}
	
	/**
	 * This function is for accept rate change
	 @author leo
	 */
	public function changeRateApprovalAction(){
		
		$rate = new Model_DbTable_Roster_Staffrate();
		$stfInfo = new Model_DbTable_Roster_Staffinfo();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$mail = new Model_Emailshandler();
		$dateToday = Model_DatetimeHelper::dateToday();
		$mailAdd = 'simon.phonecollection@gmail.com;admin@phonecollection.com.au;payroll@phonecollection.com.au';
		$type = unserialize(PAYROLL_TYPE);
		$rateApp = $rate->listAllPending();
		$rateResult = $rate->listAllResult();
		$this->view->list = $rateApp;
		$this->view->result = $rateResult;
		
		if(isset($_POST['accept'])){
			if(!empty($_POST['password'])){
				$password = $_POST['password'];
				$idStaffRow = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
				if($idStaffRow){
					if(!empty($_POST['checkBox'])){
						$title = "Staff Rate Change Approve";
						$str = "Hi, staff as below rate change has approved<br/>";
						
						foreach($_POST['checkBox'] as $k => $v){
							$stf = $stfInfo->getStaffinfo($v);
							$ni = $stfDetail->getDetail($v);

							$rate->updateResult($k, $dateToday, $idStaffRow['ni'], 'Accept',$stf['new_rate'],$stf['id_package'],$_POST['newRate'][$k],$_POST['newRateType'][$k],$_POST['reason'][$k]);
							
							$stfInfo->updatePaymentInfo($stf['id_staff'], $stf['new_rate'], $stf['new_rate_date'], $_POST['newRate'][$k], $_POST['effDate'][$k]);
							$stfInfo->updateCheckStatus($stf['id_staff'], 'rate');
							if($stf['id_package'] != $_POST['newRateType'][$k]){
								$stfInfo->updateMyobInfor($stf['id_staff'],$stf['id_card'] ,$stf['id_record'], $stf['id_record_cash'], $_POST['newRateType'][$k], $_POST['effDate'][$k], $stf['id_package'], $stf['new_package_date']);
								$stfInfo->updateCheckStatus($stf['id_staff'], 'type');
							}
						
							$str .= "Staff:".$stf['first_name']." ".$stf['last_name']."( ".$ni['ni']." )<br/>"." rate ".$stf['old_rate']." -> ".$_POST['newRate'][$k]."<br/>Type:".$type[$stf['id_package']][1]." -> ".$type[$_POST['newRateType'][$k]][1]."<br/>"
							."Effective Date:".$_POST['effDate'][$k]."<br/>";

						}
						$str .= "Application has approved <br/> If you have any question , please contact head office.";
			
						$mail->sendNormalEmail($mailAdd, $title, $str);
						
					}
				}else{
					echo '<script>alert("Wrong Password!!");</script>';
					return false;
				}
				
			}
			$url = "/rosteraudit/change-rate-approval";
			$this->_redirect($url);
		}
		
		if(isset($_POST['reject'])){
			if(!empty($_POST['password'])){
				$password = $_POST['password'];
				$idStaffRow = $stfDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha(trim($password)));
				if($idStaffRow){
					if(!empty($_POST['checkBox'])){
						$title = "Staff Rate Change Reject";
						foreach($_POST['checkBox'] as $k => $v){
							$stf = $stfInfo->getStaffinfo($v);
							$rate->updateResult($k, $dateToday, $idStaffRow['ni'], 'Reject',$stf['old_rate'],$_POST['reason'][$k]);
							
							$str .= "Staff:".$stf['first_name']." ".$stf['last_name']."( ".$ni['ni']." )<br/>"." rate ".$stf['old_rate']." -> ".$_POST['newRate'][$k]."<br/>Type:".$type[$stf['id_package']][1]." -> ".$type[$_POST['newRateType'][$k]][1]."<br/>"
							."Effective Date:".$_POST['effDate'][$k]."<br/><br/>"; 

						}
						$str .= "Application has rejected <br/> Reason:".$_POST['reason'][$k]."<br/>If you have any question , please contact head office.";
						$mail->sendNormalEmail($mailAdd, $title, $str);
					}
				}else{
					echo '<script>alert("Wrong Password!!");</script>';
				}
		
			}
			$url = "/rosteraudit/change-rate-approval";
			$this->_redirect($url);
		}
	}
	
	/**
	 * this function is not in good new 
	 * it summ the early late even in the attdenace recrod and give the summary 
	 */
	public function earlyLateSummaryAction(){
			
		$lastMonday = Model_DatetimeHelper::getLastWeekMonday();
		$lastSunday = Model_DatetimeHelper::getLastWeekSunday();
		$intLastMonday = Model_DatetimeHelper::tranferToInt($lastMonday);
		$intLastSunday = Model_DatetimeHelper::tranferToInt($lastSunday);

		$ele = new Model_DbTable_Roster_Earlylateevent();
		$ts = new Model_DbTable_Roster_Timesheet();
		
		$rows = $ts->listShiftWithEvent($intLastMonday, $intLastSunday); 

		$arrRes = array();
		foreach($rows as $shiftRow){
			
			
			if($shiftRow["event_on_duty"]!=null){
				$eventLine = $ele->getEarlylateevent($shiftRow["event_on_duty"]);
				if($eventLine["event_code"] == 2){
					//					
					$tmpArr = $shiftRow;
					$tmpArr[] = $eventLine["date_event"];
					$tmpArr[] = $eventLine["staff_comment"];
					$tmpArr[] = 2;
					$arrRes[] = $tmpArr;
				}
				
			}
			
			if($shiftRow["event_off_duty"]!=null){
				$eventLine = $ele->getEarlylateevent($shiftRow["event_off_duty"]);
				if($eventLine["event_code"] == 5){
					//
					$tmpArr = $shiftRow;
					$tmpArr[] = $eventLine["date_event"];
					$tmpArr[] = $eventLine["staff_comment"];
					$tmpArr[] = 5;
					$arrRes[] = $tmpArr;					
				}
			
				}			
			
		}
				
		$this->view->arrRes = $arrRes;
	}
	
	/**
	 * this is the landing page of check roster by name
	 */
	public function checkAllNamesAction(){
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$uplog = new Model_Hr_Uploadlog();
		$arrStaff = $stInfo->checkNeedVerify();
		$uniArrSt = $stInfo->checkNeedVerifyStaff($arrStaff);
		$arrStaffLog = $uplog->checkFileNeedVerify();

		$uniArrLog = $uplog->listNeedVerifyStaff($arrStaffLog);

		$arrIDStaff = array_unique(array_merge($uniArrSt,$uniArrLog));

		
		$arrRes = array();
		foreach($arrIDStaff as $id){
			
			$stLine = $stDetail->getDetail($id);
			$arrRes[] = array($id,ucwords($stLine['ni']."( ".Model_EncryptHelper::getSslPassword($stLine['n']).')'));
		}
		$this->view->arrRes = $arrRes;
		
		
	}
	
	/**
	 * This is no use once off function to import the MYOB staff
	 */
	public function zNOUSEimportMyobStaffAction(){
		
		$fh = new Model_Fileshandler();
		
		$csvFileName = getcwd()."/stafflist.csv";
		$fh->importStaffFile($csvFileName);
		
	}

	/**
	 * This function is no longer need 
	 * the function has been  included in the payroll wizard 
	 * it tell the warehouse on monday after noon
	 * who still not finish the confirm of the roster 
	 */
	public function whoIsNotFinishAction(){
		
		date_default_timezone_set('Australia/Melbourne');
		
		$theDate = (int)date("d");
		
		$arrShop = unserialize(ARR_SHOP_ACTIVE);
		$tSheet = new Model_DbTable_Roster_Timesheet();
		
		$dateToday = Model_DatetimeHelper::dateToday();
		
		$sh = new Model_DbTable_Shoplocation();
		$mail = new Model_Emailshandler();
		
		
		$arrMgrEmails = array();
		//$dayToday = date("N");
		$dayToday = $this->_getParam("day");
		$ifEmail = $this->_getParam("email");
		$missingShop = "";
		$intDateBegin = 0;
		$intDateEnd = 0;
		if($dayToday == 1){
			//do the confirm 
			
			$intDateBegin = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::getLastWeekMonday());
			$intDateEnd = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::getLastWeekSunday()) + 86400;
			
			$missingShop = $tSheet->listShopNotFinish($intDateBegin, $intDateEnd);
			
			if($ifEmail=="yes"){
				
				foreach($missingShop as $key => $v){
				$mgrEmail = $sh->getStoreManMailByHead($v["shop_head"]);
				//sending email 
				if($mgrEmail==""){
					//send to area manager email
					$mgrEmail = $sh->getAreaManMailByHead($v["shop_head"]);
				}
			
				if(!in_array($mgrEmail,$arrMgrEmails)){
					
					$subject = "Please Confirm The Roster for last week";
					$mailbody = "Dear Manager, Please confirm the Roster of your shops for last week";
					
					$mail->sendActionEmail($mgrEmail, $subject, $mailbody);
					
					echo "send to:".$mgrEmail."<br />";
					$arrMgrEmails[] = $mgrEmail;
				}	
				
				
				}
			}
		}
		if($dayToday == 5 || $theDate == 15){
			
			$intDateBegin = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::adjustWeeks("add",Model_DatetimeHelper::getThisWeekMonday(),4));
			// arrange 4 weeks
			$intDateEnd = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::adjustWeeks("add",Model_DatetimeHelper::getThisWeekSunday(),4)) + 86400;
			
			$missingShop = $tSheet->listShopNotArrange($intDateBegin, $intDateEnd);
			
			
			//var_dump($missingShop);
			
			if(!empty($missingShop)){
			foreach($missingShop as $shop){
				
				$shopHead = $shop["shop_head"];
				$key = array_search($shopHead,$arrShop,true);
				array_splice($arrShop,$key,1);
				
			}
			}
			$missingShop = $arrShop;
			
			if($ifEmail=="yes"){
			
			foreach($missingShop as $key => $v){
				$mgrEmail = $sh->getStoreManMailByHead($v);
				//sending email 
				if($mgrEmail==""){
					//send to area manager email
					$mgrEmail = $sh->getAreaManMailByHead($v);
				}
			
				if(!in_array($mgrEmail,$arrMgrEmails)){
					
					$subject = "Please Arrange The Roster For Next Month";
					$mailbody = "Dear Manager, Please arrange the roster for the next 4 weeks as requested by Head Office";
					
					$mail->sendNormalEmail($mgrEmail, $subject, $mailbody);
					
					echo "send to:".$mgrEmail."<br />";
					$arrMgrEmails[] = $mgrEmail;
				}	
				
				
				}
			}
			
		}
		
		$this->view->intDB = $intDateBegin;
		$this->view->intDE = $intDateEnd;
		$this->view->missingShop = $missingShop;
		
		// run on every friday and monday 
		//check arrange and confirm 
		
	}	
	
	/**
	 * This function is not finished YET 
	 */
	public function managerListProblemsNewAction(){

		$token = $this->_getParam("token");
		$this->view->manID = base64_decode($token);
		
		date_default_timezone_set('Australia/Melbourne');
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$atRecord = new Model_DbTable_Roster_Attnrecord();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$type = "normal";
		$arrResult = array();
		
		$arrResultMore = array();
		$arrResultLate = array();
		$arrResultChange = array();
		$arrResultMissing = array();
		
		
		if($_GET){
				
			$dateBegin = $_GET["date_begin"];
			$dateEnd = $_GET["date_end"];

			$intDateBegin = Model_DatetimeHelper::tranferToInt($dateBegin);
			$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd) + 86400;
				

			$shiftList = $tSheet->listShiftByDate($dateBegin, $dateEnd);
				
			foreach($shiftList as $shift){
				
				$tmpArr = $shift;
				$idStaff = $shift["id_staff"];
				$shopHead = Model_EncryptHelper::sslPassword($shift["shop_head"]);
				$dateCheck = date("Y-m-d",$shift["shift_begin"]);
				
				$attLine = $atRecord->getFirstOnLastOffDuty($idStaff, $dateCheck, $shopHead);
				
				$tmpArr["on_duty"] = $attLine[0];
				$tmpArr["off_duty"] = $attLine[1];
				$tmpArr["error"] = "";
				
				if($shift["confirm_shift_begin"]!= null && $shift["confirm_shift_end"]!= null){ // Manager Has Confirmed
					
					// staff work more 
					
					// staff late 
					
					// satff shift change 
					
					// missing record 
					
					
				
					if($attLine[0]=="" || $attLine[1]=="" || ($attLine[1] - $attLine[0]) < 240 ){ // attendance record missed, for sure not going to pay
						$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">YES</div>','<div style="width:120px;; background-color:#AAFFB7">In Complete</div>','<div style="width:120px;; background-color:#FEBCBA">NO,Create Case</div>');
						
						if(!($shift["confirm_shift_begin"] == $shift["confirm_shift_end"] && $attLine[0] == "" && $attLine[1] == "")){
							$arrResultMissing[]=$tmpArr;
						}
					}
					else{
						
						$compareOnDuty = $shift['confirm_shift_begin'] - $attLine[0];
						$compareOffDuty = $shift['confirm_shift_end'] - $attLine[1];
						
						$disOnDuty = abs($compareOnDuty);
						$disOffDuty = abs($compareOffDuty);

						//15 min 59 seconds is 959 seconds	
						if($compareOnDuty > 959 && $disOffDuty <= 959 ){
							//come early than 15 mins 
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">YES, Not Match </div>','<div style="width:120px;; background-color:#AAFFB7">Complete</div>','<div style="width:120px;; background-color:#FEBCBA">NO,May Cause Issue</div>');
							$arrResultMore[] = $tmpArr;
						}
						elseif($compareOffDuty < -959 && $disOnDuty <=959){
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">YES, Not Match </div>','<div style="width:120px;; background-color:#AAFFB7">Complete</div>','<div style="width:120px;; background-color:#FEBCBA">NO,May Cause Issue</div>');
							$arrResultMore[] = $tmpArr;
							
							// leave Late
						}
						
						elseif(($compareOnDuty < - 959 && $disOffDuty <= 959 ) || ( $compareOffDuty > 959 && $disOnDuty <=959)){
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">YES</div>','<div style="width:120px;; background-color:#AAFFB7">Complete</div>','<div style="width:120px;; background-color:#FEBCBA">NO,Confirm LATE/EARLY </div>');
							$arrResultLess[] = $tmpArr;
							//come late or leave early
							
						}
						
						elseif( $disOnDuty > 959 && $disOffDuty > 959 ){
							// change shift
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">YES, Not Match</div>','<div style="width:120px;; background-color:#AAFFB7">Complete</div>','<div style="width:120px;; background-color:#FEBCBA">NO,CHANGE SHIFT / ACCEPT</div>');
							$arrResultChange[] = $tmpArr;
							
						}
			
						
						
						
						
						
						// This is default rule
						//if(abs($shift['confirm_shift_begin'] - $attLine[0]) > 959 || abs($shift['confirm_shift_end'] - $attLine[1]) > 959 ){
				
						//	$tmpArr["error"] = array('<div style="width:120px;; background-color:#FDF7AC">YES,NotMatch</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
						//	$arrResult[]=$tmpArr;
						//}		
					}
				}				
				
			}
			
		   }		

		$stIds = array();
		$dates = array();
		
		foreach($arrResultMissing as $k => $v){
			
		$stIds[$k] = $v["id_staff"];
		$dates[$k] = $v["confirm_shift_begin"];
		}
		
		array_multisort($stIds,SORT_ASC,$dates,SORT_ASC,$arrResultMissing);

		$stIds = array();
		$dates = array();
		
		foreach($arrResultMore as $k => $v){
				
			$stIds[$k] = $v["id_staff"];
			$dates[$k] = $v["confirm_shift_begin"];
		}
		array_multisort($stIds,SORT_ASC,$dates,SORT_ASC,$arrResultMore);		
		
		$stIds = array();
		$dates = array();
		
		foreach($arrResultLess as $k => $v){
				
			$stIds[$k] = $v["id_staff"];
			$dates[$k] = $v["confirm_shift_begin"];
		}
		array_multisort($stIds,SORT_ASC,$dates,SORT_ASC,$arrResultLess);
		
		$stIds = array();
		$dates = array();
		
		foreach($arrResultChange as $k => $v){
				
			$stIds[$k] = $v["id_staff"];
			$dates[$k] = $v["confirm_shift_begin"];
		}
		array_multisort($stIds,SORT_ASC,$dates,SORT_ASC,$arrResultChange);
		
		$this->view->arrResultMissing = $arrResultMissing;		
		$this->view->arrResultMore = $arrResultMore;
		$this->view->arrResultLess = $arrResultLess;
		$this->view->arrResultChange = $arrResultChange;
		
	}
	
	/**
	 * This is the current using funcion of manager listing problem
	 * after manager "SAVE" the roster , the manager can see the problems of the 
	 * selected date and selected staff then they can create the case for them 
	 */
	public function managerListProblemsAction(){
		

		
		$token = $this->_getParam("token");
	
		//$token = base64_encode("1");
		$this->view->manID = base64_decode($token);
		
		date_default_timezone_set('Australia/Melbourne');
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$atRecord = new Model_DbTable_Roster_Attnrecord();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$this->view->stList = $stDetail->listStaffByNickName();
		
		
		$type = "normal";
		$arrResult = array();
		$this->view->arrShopList = unserialize(ARR_MANAGER);
		if($_GET){
			
			$dateBegin = $_GET["date_begin"];
			$dateEnd = $_GET["date_end"];
			//$type = $_GET["type"];
			$intDateBegin = Model_DatetimeHelper::tranferToInt($dateBegin);
			$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd) + 86400;
			$missingShops = $tSheet->listShopNotFinish($intDateBegin, $intDateEnd);
			$this->view->missingShops = $missingShops;
			
		// 
			$shiftList = $tSheet->listShiftByDate($dateBegin, $dateEnd);
			foreach($shiftList as $shift){
				
				if( $_GET["staff_name_1"]=="All" || $_GET["staff_name_1"] == $shift["id_staff"]){
				
				
				$tmpArr = $shift;
				$idStaff = $shift["id_staff"];
				$shopHead = Model_EncryptHelper::sslPassword($shift["shop_head"]);
				$dateCheck = date("Y-m-d",$shift["shift_begin"]); 
				
				
				$attLine = $atRecord->getFirstOnLastOffDuty($idStaff, $dateCheck, $shopHead);
				$tmpArr["on_duty"] = $attLine[0];
				$tmpArr["off_duty"] = $attLine[1];
				$tmpArr["error"] = "";
			

				if($shift["confirm_shift_begin"]!= null && $shift["confirm_shift_end"]!= null){
					//staff shift login match staff actuall login do not match manage , manager did not do change web we can change
				
					if(
						($shift["confirm_shift_begin"] != $shift["shift_begin"] || $shift["confirm_shift_end"] != $shift["shift_end"]) 
						&& ($attLine[0]!="" && $attLine[1]!="" )
						&& ($shift["confirm_shift_begin"] != $shift["confirm_shift_end"])
					) {
						$afftectHours = 0;
						//$tmpArr["error"] .= "Mgr Assign Diff Time Period,Calculate Base On Mgr,BUT Need Send to Mgr Confirm";
						$tmpArr["error"] = array('<div style="width:120px;; background-color:#FDF7AC">YES,NotMatch</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>');
						
						$tmpArr['err_des'] = "The Shift Time Manager Confirmed is Different Form Staff Input, Please Verify It";
						$tmpArr['affect_hour'] = "-";					
						//$arrResult[]=$tmpArr;
					}
					if( $shift["confirm_shift_end"] - $shift["confirm_shift_begin"] >= 34200){
						
						$tmpArr["error"] = array('<div style="width:120px;; background-color:#FDF7AC">Over 9.0 Hour </div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>');
						
						$tmpArr['err_des'] = "NO CASE NECESSARY,Just A Notice";
						$tmpArr['affect_hour'] = "-";						
						//$arrResult[]=$tmpArr;
					}
					//manager do not allocate time , it has the actually login , we can change it
					if(($shift["confirm_shift_begin"] == $shift["confirm_shift_end"]) && ($attLine[0] != "" && $attLine[1]!="")){
						
						//check if all the record is calculated 
						//var_dump($idStaff, $shopHead, $dateCheck, $dateCheck);
						$staffShiftList = $tSheet->listAllShiftByStaffIdByDateByShop($idStaff,$shift["shop_head"], $dateCheck, $dateCheck);
			
						$allEmpty = true;
							
						
							//var_dump($staffShiftList);
							
							if($staffShiftList){	
							foreach($staffShiftList as $k2 => $v2){
								
								//var_dump($v2);
							
								if($v2["confirm_shift_begin"] != $v2["confirm_shift_end"]){
									$allEmpty = false;	
								}
							}
							}
							
						if($allEmpty){
							//$tmpArr["error"] = "Staff Come,But Mgr NOT Allocate,Will NOT Calculate, Need Send to Mgr Confirm";
							$tmpArr["error"] = array('<div style="width:120px; background-color:#FEBCBA">NO</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
							$tmpArr["err_des"] = 'No Roster Allocated By Manager';
							$tmpArr['affect_hour'] = '-';
						
						$arrResult[]=$tmpArr;
						}
						
					}
					//both manager and staff did not do job well
					if(($shift["confirm_shift_begin"] == $shift["confirm_shift_end"]) && ($attLine[0] == "" || $attLine[1]=="") && ($attLine[0] != $attLine[1])){
						
						$staffShiftList = $tSheet->listAllShiftByStaffIdByDateByShop($idStaff,$shift["shop_head"], $dateCheck, $dateCheck);
						$allEmpty = true;
						//echo "L2:";
						//var_dump($staffShiftList);
						if($staffShiftList){
						foreach($staffShiftList as $k2 => $v2){
							//var_dump($v2);
							if($v2["confirm_shift_begin"] != $v2["confirm_shift_end"]){
								$allEmpty = false;
							}
						}
						}
						if($allEmpty){
							//$tmpArr["error"] = "Mgr NOT Allocate, Staff Also Missing Record, Will Not Calculate, Need Send to Mgr Confirm";
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">NO</div>','<div style="width:120px;; background-color:#FDF7AC">MAY BE</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
							$tmpArr["err_des"] = 'No Roster Allocated By Manager And Staff Missing Attendance';
							$tmpArr['affect_hour'] = '-';
					
					
							
						$arrResult[]=$tmpArr;
						}
						
					}
					// staff did not do job well , missing login record 
					if(($shift["confirm_shift_begin"] != $shift["confirm_shift_end"]) && ($attLine[0] == "" || $attLine[1]=="")){
					
						//$tmpArr["error"] = "Staff Missing Record, Will Not Calculate,Need Send to Mgr Confirm";
						
						$tmpArr["error"] = array('<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FDF7AC">MAY BE</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
						$tmpArr["err_des"] = 'Missing Attendance Record';
						$tmpArr['affect_hour'] = '-';
						
						
						
						if($attLine[0] == "" && $attLine[1]=="" ){
						
						$tmpArr["error"] = array('<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FEBCBA">NO RECORD</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
						$tmpArr["err_des"] = 'Staff Never Turn up in the shift';
						$tmpArr['affect_hour'] = '-';
						}
						
						$arrResult[]=$tmpArr;
					
					}
					
					// staff Late 
					if(($shift["confirm_shift_begin"] != $shift["confirm_shift_end"]) && ($attLine[0] != "" && $attLine[1]!="")
								
							&&( ($attLine[0] > ($shift["confirm_shift_begin"] + 300) ) || ( $attLine[1] <  ($shift["confirm_shift_end"] - 300) ) )
					){
					
						$affectTime = 0;
					
						//d($attLine[0] -  $shift["confirm_shift_begin"]);
					
						if( $attLine[0] > ( $shift["confirm_shift_begin"] + 300 ) ){
								
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FDF7AC">YES</div>','<div style="width:120px;; background-color:#FEBCBA">YES, BUT WILL DEDUCT TIME</div>');
							$tmpArr["err_des"] = 'You Come Late';
							
							$affectTime += $attLine[0] -  $shift["confirm_shift_begin"];
							$tmpArr['affect_hour'] = round($affectTime/3600,2);
						}
						//	d($shift["confirm_shift_end"] - $attLine[1]);
						if( $attLine[1] < ( $shift["confirm_shift_end"] - 300 ) ){
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FDF7AC">YES</div>','<div style="width:120px;; background-color:#FEBCBA">YES, BUT WILL DEDUCT TIME</div>');
							$tmpArr["err_des"] = 'Left Early';
								
							$affectTime += $shift["confirm_shift_end"] - $attLine[1];
							$tmpArr['affect_hour'] = round($affectTime/3600,2);
						}
					
						$arrResult[]=$tmpArr;

					}
					}
			
			}
			}
			
		
		}	

		$erros = array();
		$stIds = array();
		$dates = array();

		foreach($arrResult as $k => $v){

			$erros[$k] = $v["error"];
			$stIds[$k] = $v["id_staff"];
			$dates[$k] = $v["confirm_shift_begin"];
		}
		
		array_multisort($stIds,SORT_ASC,$dates,SORT_ASC,$erros,SORT_ASC,$arrResult);
		$this->view->arrResult = $arrResult;		
	
			
		
	}
	

	
	/**
	 * This is the page for manager to check the case handling result 
	 */
	
	public function managerCaseControlAction(){
		
		$idMgr = 0;
		$idMgr = base64_decode(trim($this->_getParam("token")));
		
		
		$attCase = new Model_DbTable_Roster_Attncase();
		$acRecord = new Model_DbTable_Roster_Attcaserecord();
		$openCase = array();
		$waitCase = array();
		$rejectCase = array();
		$paidCase = array();
		
		$openCase = $attCase->listUndecidedCase();
		$waitCase = $attCase->listWillpayCase();
		$rejectCase = $attCase->listRejectCase();
		$paidCase = $attCase->listPaidCase();
		
		$this->view->openCase = $openCase;
		$this->view->waitCase = $waitCase;
		$this->view->rejectCase = $rejectCase;
		$this->view->paidCase = $paidCase;
		$this->view->mgrID = $idMgr;
		
		$this->view->arrShopList = unserialize(ARR_MANAGER);
		
	}

	/**
	 * When SU password is use in check roster by name 
	 * a new form will show in that page and submit the att record using this page
	 * then it will insert a attendance record in IP 0000 into the att record table 
	 */	
	public function insertFakeAttnRecordAction(){
		
		$attn = new Model_DbTable_Roster_Attnrecord();
		
		if($_POST && $_POST['password'] == 'Office051788'){
			
			$staffId =trim($_POST['staff_id']);
			
				date_default_timezone_set('Australia/Melbourne');
			
			if(trim($_POST['shop_code'])=="ADPC" || trim($_POST['shop_code'])=="CLPC" || trim($_POST['shop_code'])=="CLIC" || trim($_POST['shop_code'])=="WLIC"){
				
				date_default_timezone_set('Australia/Adelaide');
			}
			$shopHead =  Model_EncryptHelper::sslPassword(trim($_POST['shop_code']));
			
			$ip = '0.0.0.0';
			
			$date = trim($_POST['year'])."-".trim($_POST['month'])."-".trim($_POST['day']);
			$time = trim($_POST['hour']).":".trim($_POST['min']).":00";
			
			$intTime = date("U",strtotime($date." ".$time));
			
			$onStatus = $attn->createStatusOnDuty();
			$offStatus = $attn->createStatusOffDuty();
			$status= ($_POST['status']=="ONDUTY")?$onStatus:$offStatus;
			
			$attn->addRecord($staffId, $intTime, $ip, $shopHead, $status);
			
			echo "INSERTED";
			
		}
		
	}

	/**
	 * This function is for insert WH staff fake attend record if miss
	 * @version 2014-08-20
	 * @author Leo
	 */
	public function whFakeAttnRecordAction(){
	
		$attn = new Model_DbTable_Roster_Attnrecord();
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$sDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attCase = new Model_DbTable_Roster_Attncase();
	
	
		if($_POST){
				
			$staffId =trim($_POST['staff_id']);
			date_default_timezone_set('Australia/Melbourne');
	
			$shopHead =  Model_EncryptHelper::sslPassword(trim('WHPC'));
			$ip = '0.0.0.0';
	
			$date = trim($_POST['year'])."-".trim($_POST['month'])."-".trim($_POST['day']);
			$time = trim($_POST['hour']).":".trim($_POST['min']).":00";
	
			$intTime = date("U",strtotime($date." ".$time));
			$onStatus = $attn->createStatusOnDuty();
			$offStatus = $attn->createStatusOffDuty();
			
			if($_POST['on_status'] ==1){
				$date = trim($_POST['year'])."-".trim($_POST['month'])."-".trim($_POST['day']);
				$time = trim($_POST['hour']).":".trim($_POST['min']).":00";
				
				$intTime = date("U",strtotime($date." ".$time));
				$attn->addRecord($staffId, $intTime, $ip, $shopHead, $onStatus);
			}
			if($_POST['off_status'] ==1){
				$date = trim($_POST['year'])."-".trim($_POST['month'])."-".trim($_POST['day']);
				$time = trim($_POST['hour2']).":".trim($_POST['min2']).":00";
				
				$intTime = date("U",strtotime($date." ".$time));
				$attn->addRecord($staffId, $intTime, $ip, $shopHead, $offStatus);
			}
			
			//2014-08-21
			
			$url = "/rosteraudit/payroll-wizard-hq/date_begin/".$_POST['date_begin']."/date_end/".$_POST['date_end'];
			$this->_redirect($url);
		}
	
	}
	


	/**
	 * This function is made by normal to export the single staff time sheet
	 * 
	 */
	public function exportTimeSheetSingleStaffAction(){
		

		
		date_default_timezone_set('Australia/Melbourne');		
		$arrPublicHoliday = unserialize(VIC_PUBLIC_HOLIDAY);
		$arrPublicHolidaySa = unserialize(SA_PUBLIC_HOLIDAY);
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Note","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");		
		$arrPayment = array(
				0 => array(),
				1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
				2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				7 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				8 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
		);
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);

		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$fileName = "";
		
		if($_POST){
			
			$idStaff = $_POST["id_staff"];
			
			$stRow = $stInfo->getStaffinfo($idStaff);
			$firstName = str_replace(" ","_",$stRow['first_name']);
			
			//$cardId = $_POST["card_id"];
			//$recordId = $_POST["record_id"];
			$dateEnd = $_POST["date_end"]; // exclude 
			$dateBegin = $_POST["date_begin"];
			//$idType = $_POST["id_type"];
			 
			$orgFileName = "TS_".$dateBegin."-".$dateEnd.".txt";
			
			$fileName = $idStaff."_".$stRow['last_name']."_".$firstName."_".$orgFileName;
			
			$strFileHead = implode("\t",$arrFileHead);
			$fl = fopen(getcwd()."/".$fileName,"w");
			fputs($fl,$strFileHead."\r\n");
			fclose($fl);
			
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			
			foreach($arrDate as $dateCheck){
				$finalShift = array();
				$compareHr = array();
				$compareShift = array();
				$arrShift = $tSheet->listShiftByStaffIdByDate($idStaff, $dateCheck, $dateCheck);
				if(!empty($arrShift)){
				if(count($arrShift) > 1){
					foreach ($arrShift as $k => $v){
						$hour = ($v['confirm_shift_end'] - $v['confirm_shift_begin'])/3600;
						if($hour != 0){
							$compareHr[$v['shop_head']][] = $hour;
							$compareShift[$v['shop_head']][] = $v;
						} 
					}

					foreach ($compareShift as $shopName => $shopRoster){
						if(count($shopRoster) > 1){
							
							$hr = ($shopRoster[0]['confirm_shift_end'] - $shopRoster[0]['confirm_shift_begin'])/3600;
							$finalShift[$shopName] = $shopRoster[0];
							foreach ($shopRoster as $k => $v){
								$tmpHr = ($v['confirm_shift_end'] - $v['confirm_shift_begin'])/3600;
								if($tmpHr < $hr){
									$hr = $tmpHr;
									$finalShift[$shopName] = $v;
								}
								
							}
						}else{
							$finalShift[$shopName] = $shopRoster[0];
						}
					}
				}else{
					$finalShift[$arrShift[0]['shop_head']] = $arrShift[0];
				}
				}
				
				
				$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
		
		if(!empty($finalShift)){		

				foreach($finalShift as $k => $v){
		
					$errorFlag = 0;
						
					$staffID = $v["id_staff"];
					$shopHead = $v["shop_head"];
					$attLine = $attRecord->getFirstOnLastOffDuty($staffID, $dateCheck,Model_EncryptHelper::sslPassword($shopHead));
					$stLine = $stDetail->getDetail($staffID);
					$stInfoLine = $stInfo->getStaffinfo($staffID);
					if(!$stLine || !$stInfoLine){
						$errorFlag = 1;
						$fullName = Model_EncryptHelper::getSslPassword($stLine["n"]);
				
						echo "ERROR-".$staffID."-".$stLine["ni"]."-".$fullName."<br />";
					}
						
					else{
				
						//staff Name
						$statusLine = $dateCheck.", for ".$stLine["ni"]."-".Model_EncryptHelper::getSslPassword($stLine["n"]);
				
						$fullName = explode(" ",Model_EncryptHelper::getSslPassword($stLine["n"]));
				
						$firstName = $stInfoLine["first_name"];
						$lastName = $stInfoLine["last_name"];
						$cardID = $stInfoLine["id_card"];
						$recordID =  $stInfoLine["id_record"];
						$activeStaff = 1;
						$idPackage = $stInfoLine["id_package"];
							
						if($idPackage == 2 || $idPackage == 5){
							$recordID =  $stInfoLine["id_record_cash"];
						}
						
				
						$strDate = date("j/m/Y",strtotime($dateCheck));
				
						$firstBreak = 0;
						$breakTime = 1800;
						$firstBreakStr = "";
						if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
							$breakTime  = 0;
						}
						if((($v["confirm_shift_end"]-$v["confirm_shift_begin"])<18000) && ($v["break_time"] == 0 ||$v["break_time"]== null )){
								
							$breakTime = 0;
						}
						
						if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 18000){
							if($breakTime < 1800){
								$breakTime = 1800;
								$firstBreakStr = "Over 5 Hour , Will Dedute By 0.5 Hr <br />";
							}
							//"FIRST BREAK".$firstBreak."<br />";
						}
						
				
						if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 32400){
								
							$firstBreak = 1800;
							$firstBreakStr = "Over 9Hour , Will Dedute Another 0.5 Hr <br />";
							//"FIRST BREAK".$firstBreak."<br />";
						}
						$manShiftBegin = $v["confirm_shift_begin"];
						$manShiftEnd = $v["confirm_shift_end"];
				
						$statusLine .= ",Manager Allocate Time is :".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd);
						$statusLine .= ",Staff Self Fill Time is :".date("H:i",$v["shift_begin"])."-".date("H:i",$v["shift_end"]);
						$statusLine .= ",Break Time is:".$breakTime/60;
				
						$actBegin = $attLine[0];
						$actEnd = $attLine[1];
				
						$statusLine .=",Staff Actually Come On :";
						$statusLine .= ($actBegin=="")?"[NO COME RECORD]":date("H:i",$actBegin);
						$statusLine .=" and Actally Leave On :";
						$statusLine .=($actEnd=="")?"[NO LEAVE RECORD]":date("H:i",$actEnd);
						$statusLine .=", Total Hrs Allocated is: ".($manShiftEnd-$manShiftBegin)/3600;
						$statusLine .=", After Break ,It change to:".($manShiftEnd-$manShiftBegin-$breakTime)/3600;
				
						$afterFix = "[S]".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd)."[B]".round($breakTime/3600,2);
				
						if($manShiftBegin!= null && $actBegin!="" && ( $actBegin > ($manShiftBegin + 300))){
				
							$manShiftBegin = $actBegin;
							$afterFix.="[LA]".round(($actBegin-$v["confirm_shift_begin"])/3600,2);
							$statusLine .="Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".round(($actBegin-$v["confirm_shift_begin"])/60,0)." mins";
							/*
							 if(($actBegin - $manShiftBegin) > 599 && ($actBegin - $manShiftBegin) <=900  ){
							$manShiftBegin += 900;
							$afterFix.="[LA]15";
				
							$statusLine .="Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct 15 mins";
							}
								
							if(($actBegin - $manShiftBegin) > 900 ){
							if(($actBegin-$manShiftBegin)%900 <= 60){
							$manShiftBegin += (($actBegin - $manShiftBegin) - ($actBegin - $manShiftBegin)%900);
							$afterFix.="[LA]".round((($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"]) % 900 ) /3600,2);
							$statusLine .= "Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".(($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"] ) %900 ) / 60 ." mins";
							}
							else{
							$manShiftBegin += (($actBegin - $manShiftBegin) - ($actBegin - $manShiftBegin)%900)+ 900;
							$afterFix.="[LA]".round(((($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"])%900)+ 900)/3600,2);
							$statusLine .= "Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".(($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"] ) %900 ) / 60 ." + 15 mins";
							}
							}
							*/
							
						}
				
						if($actEnd!="" && $manShiftEnd!= null && ( ($actEnd + 300) < $manShiftEnd) ){
								
							$manShiftEnd = $actEnd;
							$afterFix .="[EL]".round(($v["confirm_shift_end"]-$actEnd)/3600,2);
							$statusLine .= ", Leave Early on  ".date("H:i",$actEnd)." so I deduct".round(($v["confirm_shift_end"]-$actEnd)/60,2)." mins";
						}
				
						$shiftBegin = $manShiftBegin;
						$shiftEnd = $manShiftEnd - $breakTime;
				
						if($actBegin=="" || $actEnd == "" || $v["confirm_shift_begin"] == null || $v["confirm_shift_end"] = null){
								
							$shiftBegin = 0;
							$shiftEnd = 0;
						}
				
				
						$adjustTime = ($v["admin_adjust"]===null)?0:$v["admin_adjust"];
						//final adjust
						$statusLine .= $firstBreakStr;
						echo $statusLine."<br />";
							
						//public holiday
						if(in_array($dateCheck,$arrPublicHoliday)){
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
				
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
				
							//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff){
								$fl = fopen(getcwd()."/".$fileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],"Time Sheet",$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
							}
								
						}
						elseif(date("N",strtotime($dateCheck)) == 7){
								
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
								
							//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff){
								$fl = fopen(getcwd()."/".$fileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],"Time Sheet",$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
							}
								
						}
						elseif(date("N",strtotime($dateCheck)) == 6){
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
								
							//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff){
								$fl = fopen(getcwd()."/".$fileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],"Time Sheet",$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
							}
						}
						else{
							//1-5
				
							if($v["shop_head"] == "ADPC" || $v["shop_head"] == "CLPC" || $v["shop_head"] == "WLIC" || $v["shop_head"] == "CLIC" ){
								$date6Pm = date("U",strtotime($dateCheck." 18:30:00"));
							}
							else{
									
								$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
							}
								
				
							if($shiftBegin < $date6Pm && $shiftEnd <= $date6Pm){
								// total Normal hour
								//echo "FIRST BREAK".$firstBreak."<br />";
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime -$firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff){
									$fl = fopen(getcwd()."/".$fileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],"Time Sheet",$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
								}
									
							}
							if($shiftBegin >=$date6Pm){
				
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff){
									$fl = fopen(getcwd()."/".$fileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],"Time Sheet",$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
								}
				
								//total 6 pm
				
							}
							if($shiftBegin< $date6Pm && $shiftEnd > $date6Pm){
								//before and after
								$hoursNormal = round(($date6Pm-$shiftBegin-$firstBreak)/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hoursNormal > 0 && $activeStaff){
									$fl = fopen(getcwd()."/".$fileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],"Time Sheet",$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
								}
									
								$hoursExt = round(($shiftEnd-$date6Pm)/3600,2);
								echo "Ext Hour is".$hoursExt."|";
								//$strBegin = date("H:i",$shiftBegin);
								//$strEnd = date("H:i",$shiftEnd);
								//$strStartStopTIme = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hoursExt > 0 && $activeStaff){
									$fl = fopen(getcwd()."/".$fileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],"Time Sheet",$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
								}
							}
								
						}
							
							
							
					}//end else
				}
			  
				
			}
			}
			
			echo "<br />";
			echo "<a href=\"/{$fileName}\" target=\"_blank\" >Right Click  Here And Save AS </a>";
			
		}
		
		
		
	}
	
	/**
	 *  This is main function of export the time sheet 
	 *  
	 */
	public function exportTimeSheetAction(){

		date_default_timezone_set('Australia/Melbourne');
		
		$arrPublicHoliday = unserialize(VIC_PUBLIC_HOLIDAY);
		$arrPublicHolidaySa = unserialize(SA_PUBLIC_HOLIDAY);
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
		$arrPayment = array(
				0 => array(),
				1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
				2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				7 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				8 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
		);
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();		
		
		$arrFileNames = array();
		$exportFolder = getcwd()."/export/timesheet/";
		$zipFolder =  getcwd()."/export/timesheetzip/";
		
		if($_POST){
			$dateBegin = $_POST["date_begin"];
			$dateEnd = $_POST["date_end"];
			$whOnly = $_POST["wh_staff"];
			
			$orgFileName = "TS_".$dateBegin."-".$dateEnd.".txt";
			
			foreach($arrFileNameStr as $key => $value){
			if($value!=""){	
				$fileName = $value.$orgFileName;
				$strFileHead = implode("\t",$arrFileHead);
				$fl = fopen($exportFolder.$fileName,"w");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			
			}
			}		
			
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			foreach($arrDate as $dateCheck){
				
				$arrShift = $tSheet->listShiftByDate($dateCheck, $dateCheck);
				//var_dump($arrShift);
				//get 6 pm that date 
				$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
				
				foreach($arrShift as $k => $v){
					$errorFlag = 0;
					
					$staffID = $v["id_staff"];
					$shopHead = $v["shop_head"];
					$attLine = $attRecord->getFirstOnLastOffDuty($staffID, $dateCheck,Model_EncryptHelper::sslPassword($shopHead));
					$stLine = $stDetail->getDetail($staffID);
					$stInfoLine = $stInfo->getStaffinfo($staffID);
					
					$needWarehouse = false;
					if($_POST['wh_staff'] == 1){
						if($stInfoLine['position_status']==8){
							
							$needWarehouse = false;
						}
						else{
							
							$needWarehouse = true; // igonre it 
						}
						
					}
					else{
						
						if($stInfoLine['position_status']==8 || $stInfoLine['is_wh'] == 1){
							$needWarehouse = true;
							
						}
						else{
							
							$needWarehouse = false;
						}
						
					}
					
					
					if(!$stLine || $needWarehouse){

						if(!$stLine){
						$errorFlag = 1;
						$fullName = Model_EncryptHelper::getSslPassword($stLine["n"]);
						
						echo "ERROR-".$staffID."-".$stLine["ni"]."-".$fullName."<br />";
						
						}
						else{

							$errorFlag = 2;
							
							echo "Warehouse Staff Just Ignore This Line<br />";
							
						}
					}
					
					else{

						//staff Name 
						$statusLine = $dateCheck.", for ".$stLine["ni"]."-".Model_EncryptHelper::getSslPassword($stLine["n"]);
						
						$fullName = explode(" ",Model_EncryptHelper::getSslPassword($stLine["n"]));
						
						$errorPerson = true;
						
							$firstName = $fullName[0];
							$lastName = $fullName[1];
							$cardID = ucwords(Model_EncryptHelper::getSslPassword($stLine["n"]));
							$recordID = "000";
							$activeStaff = -1;
							$idPackage = 5;
						
						if($stInfoLine){
							
							$firstName = $stInfoLine["first_name"];
							$lastName = $stInfoLine["last_name"];
							$cardID = $stInfoLine["id_card"];
							
							$activeStaff = $stInfoLine["active_staff"];
							$idPackage = $stInfoLine["id_package"];
							
							
							$recordID =  $stInfoLine["id_record"];
							
							if($idPackage == 2 || $idPackage == 5){
								$recordID =  $stInfoLine["id_record_cash"];
							}
							
							
						}
			

						
						$strDate = date("j/m/Y",strtotime($dateCheck));
						
						$firstBreak = 0;
						$breakTime = 1800;
						$firstBreakStr = "";
						if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
							$breakTime  = 0;
						}
						if((($v["confirm_shift_end"]-$v["confirm_shift_begin"])<18000) && ($v["break_time"] === (int)0 ||$v["break_time"]== null )){
							
							$breakTime = 0;
						}
						if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 18000){
							if($breakTime < 1800){
								$breakTime = 1800;
								$firstBreakStr = "Over 5 Hour , Will Dedute By 0.5 Hr <br />";
							}		
							//"FIRST BREAK".$firstBreak."<br />";
						}
						
						if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 32400){
							
							$firstBreak = 1800;
							$firstBreakStr = "Over 9Hour , Will Dedute Another 0.5 Hr <br />";
							//"FIRST BREAK".$firstBreak."<br />";
						}				
						$manShiftBegin = $v["confirm_shift_begin"];
						$manShiftEnd = $v["confirm_shift_end"];
						
						$statusLine .= ",Manager Allocate Time is :".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd);
						$statusLine .= ",Staff Self Fill Time is :".date("H:i",$v["shift_begin"])."-".date("H:i",$v["shift_end"]);
						$statusLine .= ",Break Time is:".$breakTime/60;
						
						$actBegin = $attLine[0];
						$actEnd = $attLine[1];
						
						$statusLine .=",Staff Actually Come On :";
						$statusLine .= ($actBegin=="")?"[NO COME RECORD]":date("H:i",$actBegin);
						$statusLine .=" and Actally Leave On :";
						$statusLine .=($actEnd=="")?"[NO LEAVE RECORD]":date("H:i",$actEnd);
						$statusLine .=", Total Hrs Allocated is: ".($manShiftEnd-$manShiftBegin)/3600;
						$statusLine .=", After Break ,It change to:".($manShiftEnd-$manShiftBegin-$breakTime)/3600;
						
						$afterFix = "[S]".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd)."[B]".round($breakTime/3600,2);

						if($manShiftBegin!= null && $actBegin!="" && ( $actBegin > ($manShiftBegin + 300))){

							$manShiftBegin = $actBegin;
							$afterFix.="[LA]".round(($actBegin-$v["confirm_shift_begin"])/3600,2);
							$statusLine .="Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".round(($actBegin-$v["confirm_shift_begin"])/60,0)." mins";
							/*
							if(($actBegin - $manShiftBegin) > 599 && ($actBegin - $manShiftBegin) <=900  ){
								$manShiftBegin += 900;
								$afterFix.="[LA]15";
								
								$statusLine .="Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct 15 mins";
							}
							
							if(($actBegin - $manShiftBegin) > 900 ){
								if(($actBegin-$manShiftBegin)%900 <= 60){
									$manShiftBegin += (($actBegin - $manShiftBegin) - ($actBegin - $manShiftBegin)%900);
									$afterFix.="[LA]".round((($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"]) % 900 ) /3600,2);
									$statusLine .= "Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".(($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"] ) %900 ) / 60 ." mins";
								}
								else{
									$manShiftBegin += (($actBegin - $manShiftBegin) - ($actBegin - $manShiftBegin)%900)+ 900;
									$afterFix.="[LA]".round(((($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"])%900)+ 900)/3600,2);
									$statusLine .= "Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".(($actBegin - $v["confirm_shift_begin"]) - ($actBegin - $v["confirm_shift_begin"] ) %900 ) / 60 ." + 15 mins";
								}	
							}
							*/
							
						}
						
						if($actEnd!="" && $manShiftEnd!= null && ( ($actEnd + 300) < $manShiftEnd) ){
							
							$manShiftEnd = $actEnd;		
							$afterFix .="[EL]".round(($v["confirm_shift_end"]-$actEnd)/3600,2);	
							$statusLine .= ", Leave Early on  ".date("H:i",$actEnd)." so I deduct".round(($v["confirm_shift_end"]-$actEnd)/60,2)." mins";
						}
						
						$shiftBegin = $manShiftBegin;
						$shiftEnd = $manShiftEnd - $breakTime;
						
						if($actBegin=="" || $actEnd == "" || $v["confirm_shift_begin"] == null || $v["confirm_shift_end"] = null){
							
							$shiftBegin = 0;
							$shiftEnd = 0;
						}
						
						
						$adjustTime = ($v["admin_adjust"]===null)?0:$v["admin_adjust"];
						//final adjust 
						$statusLine .= $firstBreakStr;
						echo $statusLine."<br />";
					
					//public holiday 
						if(in_array($dateCheck,$arrPublicHoliday)){
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);

							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
						
					//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");	
							if($hours > 0 && $activeStaff >-1 ){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
							}
							
						}
						elseif(date("N",strtotime($dateCheck)) == 7){
							
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
							
							//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff >-1){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
							}
							if($hours > 0 && $activeStaff== -1){
								if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
									$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
								}
								
								$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
							
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								
							}
							
							
							
						}
						elseif(date("N",strtotime($dateCheck)) == 6){
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
							
							//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff > -1){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
							}
							if($hours > 0 && $activeStaff==-1){
								if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
									$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
								}
								
								$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
							
								$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
							}
						}
						else{
						//1-5
						
							if($v["shop_head"] == "ADPC" || $v["shop_head"] == "CLPC" || $v["shop_head"] == "WLIC" || $v["shop_head"] == "CLIC" ){
								$date6Pm = date("U",strtotime($dateCheck." 18:30:00"));
							}
							else{
							
								$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
							}
							
								
							if($shiftBegin < $date6Pm && $shiftEnd <= $date6Pm){
								// total Normal hour
								//echo "FIRST BREAK".$firstBreak."<br />";
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime -$firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff >-1){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								
							}
							if($hours > 0 && $activeStaff == -1){
								if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
									$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
								}
								
								$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
						
								$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
							}							
							}
							if($shiftBegin >=$date6Pm){
								
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hours > 0 && $activeStaff >-1){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
						
							}
							if($hours > 0 && $activeStaff == -1){
								if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
									$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
								}
								
								$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
				
								$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
							}								
								//total 6 pm
								
							}
							if($shiftBegin< $date6Pm && $shiftEnd > $date6Pm){
								//before and after 	
								$hoursNormal = round(($date6Pm-$shiftBegin-$firstBreak)/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hoursNormal > 0 && $activeStaff >-1){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								
							}
							if($hoursNormal > 0 && $activeStaff == -1){
								if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
									$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
								}
								
								$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
						
								$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
							}							
								$hoursExt = round(($shiftEnd-$date6Pm)/3600,2);
								echo "Ext Hour is".$hoursExt."|";
								//$strBegin = date("H:i",$shiftBegin);
								//$strEnd = date("H:i",$shiftEnd);
								//$strStartStopTIme = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
							if($hoursExt > 0 && $activeStaff >-1){	
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;

							}
							if($hoursExt > 0 && $activeStaff == -1){
								if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
									$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
								}
								
								$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
							}
							}
							
						}
					
					}//end else
				}
			}	
		// sort name s
		
			$arrFileNames = array_unique($arrFileNames,SORT_STRING);
			
			$fileHandler = new Model_Fileshandler();
			$zipFileName = "MYOB_TS_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
			$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);	
			
			echo "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
		}
	}

		
	/**
	 * this is the functon in the case control to add comment in the case id
	 */
	public function saveAddCommAdminAction(){
		
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$idStatus = 10; // admin add comment 
		
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name_admin'],$_POST['comm_admin']);
		
		$this->_redirect("/rosteraudit/case-control");
	}
	/**
	 * this is the funciton in the case control which manager can add comment in the conversition 
	 */
	public function saveAddCommManagerAction(){
		
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$idStatus = 9; // admin add comment
		
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name_mgr'],$_POST['comm_mgr']);
		
		$this->_redirect("/rosteraudit/manager-case-control/token/".base64_encode($_POST['id_mgr']));
	}

	/**
	 * this is the fucntion when warehouse need extra picture or other evidence 
	 * it sending the request to the manager 
	 */
	public function saveRequestAction(){
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$idStatus = 4;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
		$this->_redirect("/rosteraudit/case-control");
	}
	/**
	 * warehouse can reject the case and save it to the table
	 */
	public function saveRejectAction(){
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		$idStatus = 90;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);				
		$attCase->rejectCase($_POST['id_case']);
		$this->_redirect("/rosteraudit/case-control");
		
	}
	/**
	 * warehouse accept the case when the case if resonable 
	 * when accept the case , account need to allocate the hours to the staff
	 * then hours now store in the table but not exported 
	 */
	public function saveAcceptAction(){
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		
		$idStatus = 80;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
		$attCase->acceptCase($_POST['id_case'],$_POST['normal_hour'],$_POST['pm6_hour'],$_POST['saturday_hour'],$_POST['sunday_hour'],$_POST['holiday_hour'],$_POST['date_will_pay']);
		
		$this->_redirect("/rosteraudit/case-control");
		
		//add record 
		
		// move the case into the list 
		
		//add hour into case 
		
		//add will pay date
	}
	
	/**
	 * API function for save accept case if in current payroll cycle
	 * directly export file or into pending case for mannual export
	 */
	public function payrollSaveAcceptAction(){
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
	
		$idStatus = 80;
		$dateStart = $_POST['start_date'];
		$dateEnd = $_POST['end_date'];
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
		if($_POST['shift_date'] >= $dateStart && $_POST['shift_date'] <= $dateEnd){
		
			$attCase->acceptCase($_POST['id_case'],$_POST['normal_hour'],$_POST['pm6_hour'],$_POST['saturday_hour'],$_POST['sunday_hour'],$_POST['holiday_hour'],$_POST['date_will_pay']);
			$attCase->processPayment($_POST['id_case']);

		}else{
		
			$attCase->acceptCase($_POST['id_case'],$_POST['normal_hour'],$_POST['pm6_hour'],$_POST['saturday_hour'],$_POST['sunday_hour'],$_POST['holiday_hour'],$_POST['date_will_pay']);
		}
		

		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	}
	
	/**
	 * API function for reject case
	 */
	public function payrollSaveRejectAction(){
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$shoplocation = new Model_DbTable_Shoplocation();
		$attCase = new Model_DbTable_Roster_Attncase();
		$mail = new Model_Emailshandler();
		$idStatus = 90;
		$case = $attCase->getAttncase($_POST['id_case']);
		if($case){
			$shopEmail = $shoplocation->getNameByHead($case['shop_code']);
			if($shopEmail){
				$mailbody = "Hi Manager<br/><br/>The short pay case:".$_POST['id_case']." is rejected.<br/><br/> Reason:".$_POST['comment']."<br/><br/>If you have any question,Please call Head office, Thank you.";
				$mail->sendActionEmail($shopEmail['shop_manager_email'].";".$shopEmail['shop_email'], 'Short Pay case rejected', $mailbody);
			}
		
		
			$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
			$attCase->rejectCase($_POST['id_case']);
			$dateStart = $_POST['start_date'];
			$dateEnd = $_POST['end_date'];
		}
		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	
	}
	/**
	 * API funcion for save the warehouse need requst 
	 */
	public function payrollSaveRequestAction(){
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$shoplocation = new Model_DbTable_Shoplocation();
		$attCase = new Model_DbTable_Roster_Attncase();
		$mail = new Model_Emailshandler();
		$idStatus = 4;
		$case = $attCase->getAttncase($_POST['id_case']);
		if($case){
			$shopEmail = $shoplocation->getNameByHead($case['shop_code']);
			if($shopEmail){
				$mailbody = "Hi Manager<br/><br/>The short pay case:".$_POST['id_case']." need more infomation.<br/><br/> Comment:".$_POST['comment']."<br/><br/>If you have any question,Please call Head office, Thank you.";
				$mail->sendActionEmail($shopEmail['shop_manager_email'].";".$shopEmail['shop_email'], 'Short Pay case request', $mailbody);
			}

			$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
			$dateStart = $_POST['start_date'];
			$dateEnd = $_POST['end_date'];
		}
			
		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	}
	
	/**
	 * API function for add comments of case
	 */
	public function payrollSaveAddCommAdminAction(){
	
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$idStatus = 10; // admin add comment
	
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name_admin'],$_POST['comm_admin']);
	
		$dateStart = $_POST['start_date'];
		$dateEnd = $_POST['end_date'];
			
			
		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	}
	
	/**
	 * APIC function for save cheque No. of case
	 */
	public function payrollSaveChequeAction(){
	
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
	
		$idStatus = 99;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['cheque_no']);
		$attCase->recordChequeNo($_POST['id_case'],$_POST['cheque_no']);
		$dateStart = $_POST['start_date'];
		$dateEnd = $_POST['end_date'];
			
		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	}
	
	/**
	 * API function for save delay of case
	 */
	public function payrollSaveDelayAction(){
	
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		$idStatus = 81; // admin add comment
	
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
		$attCase->delayPayment($_POST['id_case'],$_POST['date_will_pay']);
		$dateStart = $_POST['start_date'];
		$dateEnd = $_POST['end_date'];

		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	
	}
	
	/**
	 * API function fo manual export accept case
	 */
	public function payrollSaveExportAction(){
	
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
	
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
	
	
	
		$idStatus = 82;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],"");
		$attCase->processPayment($_POST['id_case']);
	
		$dateToday = Model_DatetimeHelper::dateToday("");
		$fileName = "Shortpayment".$dateToday.".txt";
	
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
		//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Record ID");
	
		$arrPayment = array(
				0 =>array(),
				1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
				2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				7 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				8 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
		);
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);
		
		
	
		$fileNameAF = "ACDF_".$fileName;
		$fileNameBE = "BE_".$fileName;
	
		if(!file_exists(getcwd()."/".$fileNameAF)){
				
			$strFileHead = implode("\t",$arrFileHead);
			$fl = fopen(getcwd()."/".$fileNameAF,"w");
			fputs($fl,$strFileHead."\r\n");
			fclose($fl);
		}
		if(!file_exists(getcwd()."/".$fileNameBE)){
				
			$strFileHead = implode("\t",$arrFileHead);
			$fl = fopen(getcwd()."/".$fileNameBE,"w");
			fputs($fl,$strFileHead."\r\n");
			fclose($fl);
		}
	
	
		if($_POST){
				
			$idCase = $_POST['id_case'];
	
				
			$caseRow = $attCase->getAttncase($idCase);
	
			$idStaff = $caseRow['id_staff'];
			$caseNo = $caseRow['case_id_case'];
			$strDate = date("j/m/Y",strtotime($caseRow['shift_date']));
			$normalHour = $caseRow['hour_allocate_normal'];
			$pm6Hour = $caseRow['hour_allocate_6pm'];
			$satHour = $caseRow['hour_allocate_sat'];
			$sunHour = $caseRow['hour_allocate_sun'];
			$holidayHour = $caseRow['hour_allocate_pholiday'];
				
				
			$staffInfoLine = $stInfo->getStaffinfo($idStaff);
				
				
			$firstName = $staffInfoLine['first_name'];
			$lastName = $staffInfoLine['last_name'];
			$idPackage = $staffInfoLine['id_package'];
			$idCard = $staffInfoLine['id_card'];
			$recordID = $staffInfoLine['id_record'];
			
			if($idPackage == 2 || $idPackage == 5){
				$recordID =  $staffInfoLine["id_record_cash"];
			}
				
			if($normalHour>0){
	
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$normalHour,$caseNo,$idCard,$recordID);
	
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
					
			}
			if($pm6Hour>0){
					
	
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$pm6Hour,$caseNo,$idCard,$recordID);
	
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
	
	
			}
			if($satHour>0){
					
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$satHour,$caseNo,$idCard,$recordID);
	
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			}
			if($sunHour>0){
					
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$sunHour,$caseNo,$idCard,$recordID);
	
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			}
			if($holidayHour>0){
					
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$holidayHour,$caseNo,$idCard,$recordID);
					
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			}
				
				
			//get staff id
			//get staff infor detail
			// get type
				
				
		}
	
	
		//$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$orgFileName,"a");
		//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
		//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
		//$strTmp = implode("\t",$arrTmp);
		//fputs($fl,$strTmp."\r\n");
		//fclose($fl);
	
	
	
	
		//add record
		//change status 1
		//get file
		//append to time sheet
	
		$dateStart = $_POST['start_date'];
		$dateEnd = $_POST['end_date'];
		
		$url = "/rosteraudit/payroll-wizard-opening-case/date_begin/".$dateStart."/date_end/".$dateEnd."/next/yes";
		$this->_redirect($url);
	
	}
	
	/**
	 * This is the fucntion when warehouse accept the case however want to delay the paayment 
	 */
	public function saveDelayAction(){

		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		$idStatus = 81; // admin add comment
		
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);
		$attCase->delayPayment($_POST['id_case'],$_POST['date_will_pay']);
		
		$this->_redirect("/rosteraudit/case-control");
		
	}
	
	/**
	 * After case accepted , the account staff can export the record one by one 
	 * each export is a individual time sheet 
	 * 
	 */
	public function saveExportAction(){

		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		
		
		$idStatus = 82;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],"");
		$attCase->processPayment($_POST['id_case']);
		
		$dateToday = Model_DatetimeHelper::dateToday("");
		$fileName = "Shortpayment".$dateToday.".txt";
		
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
		//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Record ID");
		
		$arrPayment = array(
				0 =>array(),
				1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
				2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				7 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				8 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
		);
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);
		
		$fileNameAF = "ACDF_".$fileName;
		$fileNameBE = "BE_".$fileName;

		if(!file_exists(getcwd()."/".$fileNameAF)){
			
			$strFileHead = implode("\t",$arrFileHead);
			$fl = fopen(getcwd()."/".$fileNameAF,"w");
			fputs($fl,$strFileHead."\r\n");
			fclose($fl);
		}
		if(!file_exists(getcwd()."/".$fileNameBE)){
			
			$strFileHead = implode("\t",$arrFileHead);
			$fl = fopen(getcwd()."/".$fileNameBE,"w");
			fputs($fl,$strFileHead."\r\n");
			fclose($fl);		
		}		
		
		
		if($_POST){
			
			$idCase = $_POST['id_case'];

			
			$caseRow = $attCase->getAttncase($idCase);

			$idStaff = $caseRow['id_staff']; 
			$caseNo = $caseRow['case_id_case'];
			$strDate = date("j/m/Y",strtotime($caseRow['shift_date']));
			$normalHour = $caseRow['hour_allocate_normal'];
			$pm6Hour = $caseRow['hour_allocate_6pm'];
			$satHour = $caseRow['hour_allocate_sat'];
			$sunHour = $caseRow['hour_allocate_sun'];
			$holidayHour = $caseRow['hour_allocate_pholiday'];
			
			
			$staffInfoLine = $stInfo->getStaffinfo($idStaff);
			
			
			$firstName = $staffInfoLine['first_name'];
			$lastName = $staffInfoLine['last_name'];
			$idPackage = $staffInfoLine['id_package'];
			$idCard = $staffInfoLine['id_card'];
			if($idPackage == 2 || $idPackage == 5){
				$recordID = $staffInfoLine['id_record_cash'];
			}else{
				$recordID = $staffInfoLine['id_record'];
			}
			
			
			if($normalHour>0){
				
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$normalHour,$caseNo,$idCard,$recordID);
				
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			
			}
			if($pm6Hour>0){
			
				
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$pm6Hour,$caseNo,$idCard,$recordID);
				
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
				
				
			}
			if($satHour>0){
			
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$satHour,$caseNo,$idCard,$recordID);
				
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			}
			if($sunHour>0){
			
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$sunHour,$caseNo,$idCard,$recordID);
				
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			}
			if($holidayHour>0){
					
				$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$holidayHour,$caseNo,$idCard,$recordID);
			
				$strFileHead = implode("\t",$arrTmp);
				$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$fileName,"a");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
			}					
			
			
			//get staff id
			//get staff infor detail 
			// get type 
			
			
		}
		
		
		//$fl = fopen(getcwd()."/".$arrFileNameStr[$idPackage].$orgFileName,"a");
		//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
		//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
		//$strTmp = implode("\t",$arrTmp);
		//fputs($fl,$strTmp."\r\n");
		//fclose($fl);
		
		
		
		
		//add record 
		//change status 1
		//get file 
		//append to time sheet 
		
		
		$this->_redirect("/rosteraudit/case-control");
		
	}
	
	/**
	 * this is the final step to fullfill the payment 
	 * after payment is done , there should be a cheque in myob 
	 * the account should record the cheque no to proof it has been paid 
	 */
	public function saveChequeAction(){
		
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		
		$idStatus = 99;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['cheque_no']);
		$attCase->recordChequeNo($_POST['id_case'],$_POST['cheque_no']);
				
		$this->_redirect("/rosteraudit/case-control");
	}
	
	/**
	 * the manager can cancel the case 
	 * when the manager fills it is a mistake
	 */
	public function saveCancelAction(){
		
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		
		$idStatus = 92;
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment']);			
		$attCase->cancelCase($_POST['id_case']);
		$this->_redirect("/rosteraudit/manager-case-control/token/".base64_encode($_POST['id_mgr']));		
	}
	
	/**
	 * manager using this function to upload footage of the dvr
	 */
	public function saveUploadAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		$attCaseRecord = new Model_DbTable_Roster_Attcaserecord();
		$attCase = new Model_DbTable_Roster_Attncase();
		
		$timeStamp = date("U");
		$idStatus = 5;
		$linkImage = "";
		$cPath = getcwd();
		$uploadPath = '/upload/';
		
		if(isset($_FILES['upload_file'])){
			
			if($_POST['on_off_duty'] == 'onduty'){
				$fileName = $_FILES['upload_file']['name'];
				$ext = pathinfo($fileName, PATHINFO_EXTENSION);
				$caseId = $attCase->getAttncase($_POST['id_case']);
				$newFileName = $caseId['case_id_case']."_on".".".$ext;
				$uploadPath = '/upload/onduty/';
				if(move_uploaded_file($_FILES['upload_file']['tmp_name'],$cPath.$uploadPath.$newFileName)){
				
					$linkImage = $uploadPath.$newFileName;
				}
				$attCase->updateLinkImage($_POST['id_case'], 'onduty', $linkImage);
			}else if($_POST['on_off_duty'] == 'offduty'){
				$fileName = $_FILES['upload_file']['name'];
				$ext = pathinfo($fileName, PATHINFO_EXTENSION);
				$caseId = $attCase->getAttncase($_POST['id_case']);
				$newFileName = $caseId['case_id_case']."_off".".".$ext;
				$uploadPath = '/upload/offduty/';
				if(move_uploaded_file($_FILES['upload_file']['tmp_name'],$cPath.$uploadPath.$newFileName)){
				
					$linkImage = $uploadPath.$newFileName;
				}
				$attCase->updateLinkImage($_POST['id_case'], 'offduty', $linkImage);
			}else{ 
				$fileName = $_FILES['upload_file']['name'];
				$ext = pathinfo($fileName, PATHINFO_EXTENSION);
				$newFileName = $_POST['id_case']."_".$timeStamp.".".$ext;
				if(move_uploaded_file($_FILES['upload_file']['tmp_name'],$cPath.$uploadPath.$newFileName)){
		
					$linkImage = $uploadPath.$newFileName;
				}
			}
		}
		$attCaseRecord->addAttcaserecord($_POST['id_case'], $idStatus,Model_DatetimeHelper::dateToday(),Model_DatetimeHelper::timeNow(),$_POST['staff_name'],$_POST['comment'],$linkImage);
		$this->_redirect("/rosteraudit/manager-case-control/token/".base64_encode($_POST['id_mgr']));
	}	
	
	/**
	 * This funcion need updat, this funciton is to check manager take too many holidays
	 * @todo change manager list 
	 */
	public function checkManagerShiftAction(){
		
		$intDateToday = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::dateToday());
		
		$arrMgrList = array(3,4,27,115,131,156,165,204,312,265,276,378);
		
		$scDiff = 3600*60;
		
		$ts = new Model_DbTable_Roster_Timesheet();
		
		foreach($arrMgrList as $idMgr){
		
		$arrTs = $ts->listFutureShift($idMgr, $intDateToday);
		$errFlag = false;
		$oldBegin = 0;
		$newBegin = 0;
		
		
		foreach($arrTs as $key => $v){
			if($oldBegin >0){
				
				$newBegin = $v['arra_shift_begin'];
				
				if( ($oldBegin - $newBegin) >= $scDiff ){
					$errFlag = true;
					
					echo $idMgr."<br />";
					echo date("Y-m-d",$oldBegin);
					echo "<br/>";
					echo date("Y-m-d",$newBegin);
					echo "<br/>";
				}
				$oldBegin = $newBegin;
			}	
			else{
				
				$oldBegin = $v["arra_shift_begin"];
			}
			
			
		}
		}
		
		if($errFlag){
			$mail = new Model_Emailshandler();
			$mail->sendNormalEmail("office@phonecollection.com.au","Got To Have a Check,Shop Manager 2 Days Break In a Roll","http://".WEB_IP."/rosteraudit/check-manager-shift");
			
		}
		
		//var_dump($errFlag);
	
	}
	
	/**
	 * if staff lost password using this function to reset password to 
	 * PWDRESET then staff and change again by them self
	 */
	public function resetPwdAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		$oldPwd = new Model_System_Oldpwd();
		
		$token = $this->_getParam("token");
		$idStaff = $this->_getParam("sid");
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		if($token == Model_DatetimeHelper::dateToday()){
			
			$pwd = $stDetail->getDetail($idStaff);

			$oldPwd->addOldpwd($idStaff, $pwd['p']);
			
			$newPwd = "PWDRESET".date('U');
			
			$stDetail->updatePassword($idStaff, $newPwd);
		
			echo "STAFF ID:".$idStaff."PWD RESET DONE";
		}
		
		
	}
	/**
	 * this is the personal info page 
	 * this should all the necessary information of a person
	 * @author Norman
	 * @todo  When the person set to active , revise what disable to do 
	 */
	public function updatePersonInfoAction(){
		
		
		$strID = $this->_getParam("stid");
		
		
		date_default_timezone_set("Australia/Melbourne");
		
		$idStaff = base64_decode($this->_getParam("stid"));
		
		$cpath = getcwd();
		$pFile = '/personFile/';
		$idDir = $idStaff.'/';
		
		
		
		$dlFileName = $idStaff."_driver_license.jpg";
		$psFileName = $idStaff."_passport.jpg";
		$pvFileName = $idStaff."_passport_visa.jpg";
		$stCardFileName = $idStaff."_student_card.jpg";
		$mcCardFileName = $idStaff."_medicare_card.jpg";
		$cdCardFileName = $idStaff."_credit_card.jpg";
		
		
		$this->view->dlFileExist = (file_exists($cpath.$pFile.$idDir.$dlFileName))?$pFile.$idDir.$dlFileName:'';
		$this->view->psFileExist = (file_exists($cpath.$pFile.$idDir.$psFileName))?$pFile.$idDir.$psFileName:'';
		$this->view->pvFileExist = (file_exists($cpath.$pFile.$idDir.$pvFileName))?$pFile.$idDir.$pvFileName:'';
		$this->view->stCardFileExist = (file_exists($cpath.$pFile.$idDir.$stCardFileName))?$pFile.$idDir.$stCardFileName:'';
		$this->view->mcCardFileExist = (file_exists($cpath.$pFile.$idDir.$mcCardFileName))?$pFile.$idDir.$mcCardFileName:'';
		$this->view->cdCardFileExist = (file_exists($cpath.$pFile.$idDir.$cdCardFileName))?$pFile.$idDir.$cdCardFileName:'';
		
		
		
		if(trim($strID) == '' || !is_numeric($idStaff)){
			$this->_redirect('/rosteraudit/check-all-names');
		}
		
		if(is_numeric($idStaff) && !isset($_COOKIE["readonly"])){
			echo "I did not see read only";
			//d($_COOKIE);
			$this->_redirect('/rosteraudit/update-person-info-check-password/stid/'.$strID);
			
		}
			
		$this->view->showPassword = false;
		if(isset($_COOKIE['readonly'])){
			
			if($_COOKIE['readonly'] == 'readonlyModify'){
				
				$this->view->showPassword = true;
			}
			
		}
		
		
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$superComp = new Model_Payroll_Supercomp();
		$payMethod = new Model_Payroll_Superpaymethod();
		$leave = new Model_Hr_Staffleave();
		
		$this->view->spList = $superComp->listAll();
		$this->view->pmList = $payMethod->listAll();
		$this->view->leaveList = $leave->getPaidByStaff($idStaff);

		$this->view->wStr = '<span style="color:#990033" >Read Only Information,You CANNOT Modify It</span>';
		$this->view->enableSave = false;
		
		$oldStDetail = $stInfo->getStaffinfo($idStaff);
		$stDetailBefore =  $stDetail->getDetail($idStaff);
		
		$stfAllowance = new Model_Payroll_Staffallowance();
		$allowanceType = unserialize(ALLOWANCE_TYPE);
		
		error_reporting(E_ALL ^ E_NOTICE);
		
		if(isset($_POST['btn_submit2'])){
			$loginstaff = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['password']));
			if($loginstaff['id'] == 337 || $loginstaff['id'] == 431 || $loginstaff['id'] == 165){
			
				$this->view->wStr = '<span style = "color:#006600;">Welcome,You May Able To Modify The Information</span>';
				$this->view->enableSave = true;
			}
			
		}
		
		if(isset($_POST['save'])){
			foreach ($_POST['note'] as $k => $v){
					$leave->updateNote($k, $_POST['note'][$k]);
			}
			$url = "/rosteraudit/update-person-info/stid/".$strID;
			$this->_redirect($url);
		}
		
		if(isset($_POST['btn_submit'])){
			//d($_POST);
			
			
				
				$stInfo->updateSuperInfo($_POST['super_id_company'],$_POST['super_payment_method'], $_POST['super_acc_name'], $_POST['super_acc_no'], $_POST['super_acc_bsb'], $_POST['super_bpay_biller_code'], $_POST['super_bpay_reference'],$_POST['super_bulk_employee_id'],$_POST['super_pay_frequency'], $idStaff,$_POST['super_bulk_employer_acc_no']);
				
				$name = Model_EncryptHelper::sslPassword(strtolower(trim(str_replace(" ","",$_POST["given_name"]))." ".trim(str_replace(" ","",$_POST["surname"]))));
				$dob = Model_EncryptHelper::sslPassword($stDetail->formateDob($_POST["year"],$_POST["month"],$_POST["day"]));
					
				$stDetail->adminUpdate($idStaff, $name, $dob, ucwords(trim($_POST['pre_name'])));
					
				$stInfo->updateBasicStaffinfo($idStaff,ucwords(strtolower(trim(str_replace(" ","",$_POST["given_name"])))),ucwords(strtolower(trim(str_replace(" ","",$_POST["surname"])))),trim($_POST['gender']),trim($_POST['email_addr']),trim($_POST['mobile_no']),trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']));
				//$stInfoDetail->addStaffinfo($idStaff,trim($_POST['given_name']), trim($_POST['surname']),trim($_POST['gender']),"", 0,0, , trim($_POST['mobile_no']), trim($_POST['addr']),trim($_POST['suburb']) ,trim($_POST['state']), trim($_POST['post_code']),"", -1);
				$stInfo->updatePersonalData($idStaff, $_POST['passport_no'],$_POST['driver_license'], $_POST['visa_type'], $_POST['visa_date'],$_POST['tfn_no'],$_POST['bank_bsb'],$_POST['bank_acc_no'],$_POST['bank_acc_name'], $_POST['card_no'], $_POST['medicare_no'], $_POST['student_no']);
				$stInfo->updateMyobInfor($idStaff, trim($_POST['id_card']), trim($_POST['id_record_bank']),trim($_POST['id_record_cash']), $_POST['id_package'],$_POST['new_package_date'],$_POST['old_id_package'],$_POST['old_package_date']);
				$stInfo->updatePaymentInfo($idStaff, $_POST['old_rate'],$_POST['old_rate_date'],$_POST['new_rate'],$_POST['new_rate_date']);
				$stInfo->updateLeave($idStaff, $_POST['is_leave'], $_POST['date_leave']);
				$stInfo->updatePaperDoc($idStaff, $_POST['paper_doc_ready']);
				$stInfo->updatePosition($idStaff, $_POST['position_status']);
					
				if($_POST['is_leave']==9){
				
					// check 2 db  disactive
				
					$stDetail->disActive($idStaff);
					$stInfo->disActiveStaff($idStaff);
					// chem main db if active, send email
				}
				$newStDetail = $stInfo->getStaffinfo($idStaff);
				if($oldStDetail['new_rate'] != $newStDetail['new_rate']){
					$changes = "rate";
					$stInfo->updateCheckStatus($idStaff, $changes);
				}
				if($oldStDetail['new_package_date'] != $newStDetail['new_package_date']){
					$changes = "type";
					$stInfo->updateCheckStatus($idStaff, $changes);
				}
					
					
				echo "<div id=\"notice_1\" class = \"notice\"><h2>Staff Info Has Been Updated</h2></div>";
					
				foreach ($_POST['allow_type'] as $k => $v){
					$ammount = $_POST['allow_amt'][$k];
					$payDate = $_POST['allow_date'][$k];
					$gap = $_POST['allow_gap'][$k];
						
					if(!empty($payDate) && !empty($gap)){
						$check = $stfAllowance->getAllowanceByTypeId($idStaff, $v);
						if($ammount == 0){
							 
							$stfAllowance->deleteAllowance($idStaff, $v);
						}elseif(!$check && $ammount != 0){
							 
							$stfAllowance->addAllowance($idStaff, $v, $ammount, $payDate, $gap);
						}elseif($check){
								
							$stfAllowance->updateAllowance($check['id'], $ammount, $payDate, $gap);
						}
					}
				}
				
			//}
			
			
			
		}

		$stLine = $stInfo->getStaffinfo($idStaff);
		$stDetailLine = $stDetail->getDetail($idStaff);
		$tmpallowance = $stfAllowance->getAllowanceById($idStaff);
		foreach($tmpallowance as $k2 => $v2){
			if($v2['allowance_type'] == 1){
				$allowance1 = array($v2['allowance_amount'],$v2['allowance_pay_date'],$v2['pay_cycle_gap']);
				$this->view->allowance1 = $allowance1;
			}
			if($v2['allowance_type'] == 2){
				$allowance2 = array($v2['allowance_amount'],$v2['allowance_pay_date'],$v2['pay_cycle_gap']);
				$this->view->allowance2 = $allowance2;
			}
			
			if($v2['allowance_type'] == 3){
				$allowance3 = array($v2['allowance_amount'],$v2['allowance_pay_date'],$v2['pay_cycle_gap']);
				$this->view->allowance3 = $allowance3;
			}
			if($v2['allowance_type'] == 4){
				$allowance4 = array($v2['allowance_amount'],$v2['allowance_pay_date'],$v2['pay_cycle_gap']);
				$this->view->allowance4 = $allowance4;
			}
			if($v2['allowance_type'] == 5){
				$allowance5 = array($v2['allowance_amount'],$v2['allowance_pay_date'],$v2['pay_cycle_gap']);
				$this->view->allowance5 = $allowance5;
			}
		}

		
		$this->view->assign("stLine",$stLine);
		$this->view->nickName = ucwords($stDetailLine['ni']);
		$this->view->dob = date('Y-m-d',Model_EncryptHelper::getSslPassword($stDetailLine['d']));
		
	}
	
	/**
	 * this is private funcion write MYOB time sheet head to file 
	 * @param unknown_type $fileName
	 */
	private function writeArrHeadToFile($fileName){
		$exportFolder = getcwd()."/export/timesheet/";
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Note","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
				$strFileHead = implode("\t",$arrFileHead);
				$fl = fopen($exportFolder.$fileName,"w");
				fputs($fl,$strFileHead."\r\n");
				fclose($fl);
		
		
	}
	/**
	 * This funciton need update 
	 */
	public function whTimeAction(){
		
		$arrStaff = array(1,286,287,289,290,294,295);
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
		$attn = new Model_DbTable_Roster_Attnrecord();
		
		$arrRes = array();
		
		foreach($arrStaff as $idStaff){
			foreach($arrDate as $dateCheck){
				$arrRes[$idStaff][$dateCheck] = $attn->getFirstOnLastOffDuty($idStaff, $dateCheck,"QLJw5KUijVObUW1J8Vn3dw==");
			}
		}
		
		$this->view->arrRes = $arrRes;	
		$this->view->arrDate = $arrDate;
		
		//d($arrRes);
	}
	
	
	/**
	 * API function for showing WH Package staff time-sheet
	 @author leo
	 */
	public function payrollWizardWhSelectAction(){
		$staffInfo = new Model_DbTable_Roster_Staffinfo();
		$attSheet  = new Model_DbTable_Roster_Timesheet();
		$dateBegin = $this->_getParam("dateBegin");
		$dateEnd= $this->_getParam("dateEnd");
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		$tmpList   = $staffInfo->listAll();
		$whStaffList = array();
		foreach($tmpList as $k => $v){
			if($v['position_status']== 8 || $v['is_wh'] ==1){
				$whStaffList [] = $v;
				$sort[] = $v['id_package'];
			}
		}
		array_multisort($sort,$whStaffList);
		$this->view->staffList = $whStaffList;
		
		//show package staff roster
		if(isset($_POST['next'])){
			
			$attn 	 = new Model_DbTable_Roster_Attnrecord();
			$annualLeave = new Model_Hr_Staffleave();
			$arrRes  = array();
			$arrRes2 = array();
			$changeTypeList = array();
			$cashStaff = array();
			
			if($_POST['checkbox1']){
				foreach($_POST['checkbox1'] as $k1 => $v1){
					$idStaff = $_POST['packstaff'][$k1];
					$changeTypeList[] = $idStaff;
				}
			}
			foreach($changeTypeList as $k => $v){
				foreach($arrDate as $dateCheck){
					$leaveDetail = $annualLeave->getApproveLeaveByIdDate($v, $dateCheck);
					if($leaveDetail){
						$arrRes2[$v][$dateCheck] = $leaveDetail;
					}
					$arrRes[$v][$dateCheck] = $attn->getFirstOnLastOffDuty($v, $dateCheck,"QLJw5KUijVObUW1J8Vn3dw==");
					
				}
			}
		
			$this->view->arrRes  = $arrRes;
			$this->view->arrRes2 = $arrRes2;
			$this->view->arrDate = $arrDate;
			
		
			$this->renderScript("/rosteraudit/payroll-wizard-wh-time.phtml");
		}
		
		
		//export cash staff roster
		if(isset($_POST['export'])){
			if($_POST['checkbox2']){
				foreach($_POST['checkbox2'] as $k2 => $v2){
					$idStaff = $_POST['cashstaff'][$k2];
					$cashStaff[] = $idStaff;
				}
			}
			date_default_timezone_set('Australia/Melbourne');
			$TodayDate = date('Y-m-d', time());
			
			$arrPublicHoliday = unserialize(VIC_PUBLIC_HOLIDAY);
			$arrPublicHolidaySa = unserialize(SA_PUBLIC_HOLIDAY);
			$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
			//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Record ID");
			$arrPayment = array(
					0 => array(),
					1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
					2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
					6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
					7 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					8 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
			);
			$arrFileNameStr = unserialize(PAY_FILE_TYPE);
			
			$tSheet = new Model_DbTable_Roster_Timesheet();
			$stInfo = new Model_DbTable_Roster_Staffinfo();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			$attRecord = new Model_DbTable_Roster_Attnrecord();
			
			$arrFileNames = array();
			$exportFolder = getcwd()."/export/timesheet/";
			$zipFolder =  getcwd()."/export/timesheetzip/";

			
				$orgFileName = "TS_".$dateBegin."-".$dateEnd.".txt";
			
				foreach($arrFileNameStr as $key => $value){
					if($value!=""){
						$fileName = $value.$orgFileName;
						$strFileHead = implode("\t",$arrFileHead);
						$fl = fopen($exportFolder.$fileName,"w");
						fputs($fl,$strFileHead."\r\n");
						fclose($fl);
			
					}
				}
			
				$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
				foreach($cashStaff as $k2 => $v2){
				foreach($arrDate as $dateCheck){
					
					
					//$v = arrShift;	
					$arrShift = $tSheet->listShiftByDateId($v2, $dateCheck, $dateCheck);
	
					//var_dump($arrShift);
					//get 6 pm that date
					$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
					foreach($arrShift as $k => $v){
						$errorFlag = 0;
						$staffID = $v["id_staff"];
						$shopHead = $v["shop_head"];
						$attLine = $attRecord->getFirstOnLastOffDuty($staffID, $dateCheck,Model_EncryptHelper::sslPassword($shopHead));
						
						$stLine = $stDetail->getDetail($staffID);
						$stInfoLine = $stInfo->getStaffinfo($staffID);
						
					
						if(!$stLine){
			
							if(!$stLine){
								$errorFlag = 1;
								$fullName = Model_EncryptHelper::getSslPassword($stLine["n"]);
			
								echo "ERROR-".$staffID."-".$stLine["ni"]."-".$fullName."<br />";
			
							}
							else{
			
								$errorFlag = 2;
			
								echo "Warehouse Staff Just Ignore This Line<br />";
			
							}
						}
			
						else{
			
							//staff Name
							$statusLine = $dateCheck.", for ".$stLine["ni"]."-".Model_EncryptHelper::getSslPassword($stLine["n"]);
			
							$fullName = explode(" ",Model_EncryptHelper::getSslPassword($stLine["n"]));
			
							$errorPerson = true;
			
							$firstName = $fullName[0];
							$lastName = $fullName[1];
							$cardID = ucwords(Model_EncryptHelper::getSslPassword($stLine["n"]));
							$recordID = "000";
							$activeStaff = -1;
							$idPackage = 5;
			
							if($stInfoLine){
			
								$firstName = $stInfoLine["first_name"];
								$lastName = $stInfoLine["last_name"];
								$cardID = $stInfoLine["id_card"];
			
								$activeStaff = $stInfoLine["active_staff"];
								$idPackage = $stInfoLine["id_package"];
			
			
								$recordID =  $stInfoLine["id_record"];
			
								if($idPackage == 2 || $idPackage == 5){
									$recordID =  $stInfoLine["id_record_cash"];
								}
			
			
							}
								
			
			
							$strDate = date("j/m/Y",strtotime($dateCheck));
			
							$firstBreak = 0;
							$breakTime = 1800;
							$firstBreakStr = "";
							
							$manShiftBegin = $v["confirm_shift_begin"];
							$manShiftEnd = $v["confirm_shift_end"];
							
							$actBegin = $attLine[0];
							$actEnd = $attLine[1];
			
							if($shopHead != 'WHPC'){
								if($manShiftBegin!= null && $actBegin!="" && ( $actBegin > ($manShiftBegin + 300))){	
									$actBegin = $attLine[0];
									
								}else{
									$actBegin = $manShiftBegin;
								}
								
								if($actEnd!="" && $manShiftEnd!= null && ( ($actEnd + 300) < $manShiftEnd) ){
									$actEnd = $attLine[1];	
								}else{
									$actEnd = $manShiftEnd;
								}
							}else{
								$actBegin = $attLine[0];
								$actEnd = $attLine[1];
							}
							
							
							if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
								$breakTime  = 0;
							}
							if($actBegin != "" && $actEnd != ""){
								if((($actEnd-$actBegin)<18000) && ($v["break_time"] == 0 ||$v["break_time"]== null )){
									
									$breakTime = 0;
								}
								if(($actEnd-$actBegin) >= 32400){
										
									$firstBreak = 1800;
									$firstBreakStr = "Over 9Hour , Will Dedute Another 0.5 Hr <br />";
									//"FIRST BREAK".$firstBreak."<br />";
								}
							}
							$statusLine .= ",Break Time is:".$breakTime/60;
			
							$statusLine .=",Staff Actually Come On :";
							$statusLine .= ($actBegin=="")?"[NO COME RECORD]":date("H:i",$actBegin);
							$statusLine .=" and Actally Leave On :";
							$statusLine .=($actEnd=="")?"[NO LEAVE RECORD]":date("H:i",$actEnd);
							$statusLine .=", Total Hrs Allocated is: ".round(($actEnd-$actBegin)/3600,2);
							$statusLine .=", After Break ,It change to:".round((($actEnd-$actBegin-$breakTime)/3600),2);
							
							if($actBegin != "" && $actEnd != ""){
								$afterFix = "[S]".date("H:i",$actBegin)."-".date("H:i",$actEnd)."[B]".round(($breakTime/3600),2);
							}
			
							$shiftBegin = $actBegin;
							$shiftEnd = $actEnd - $breakTime;
			
							if($actBegin=="" || $actEnd == ""){
			
								$shiftBegin = 0;
								$shiftEnd = 0;
							}
			
			
							$adjustTime = ($v["admin_adjust"]===null)?0:$v["admin_adjust"];
							//final adjust
							$statusLine .= $firstBreakStr;
							echo $statusLine."<br />";
								
							//public holiday
							if(in_array($dateCheck,$arrPublicHoliday)){
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
			
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
			
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff >-1 ){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								}
			
							}
							elseif(date("N",strtotime($dateCheck)) == 7){
			
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
			
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff >-1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								}
								if($hours > 0 && $activeStaff== -1){
									if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
										$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
									}
			
									$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
			
								}
			
			
			
							}
							elseif(date("N",strtotime($dateCheck)) == 6){
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
			
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff > -1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								}
								if($hours > 0 && $activeStaff==-1){
									if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
										$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
									}
			
									$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
										
									$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
								}
							}
							else{
								//1-5
			
								if($v["shop_head"] == "ADPC" || $v["shop_head"] == "CLPC" || $v["shop_head"] == "WLIC" || $v["shop_head"] == "CLIC" ){
									$date6Pm = date("U",strtotime($dateCheck." 18:30:00"));
								}
								else{
										
									$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
								}
			
			
								if($shiftBegin < $date6Pm && $shiftEnd <= $date6Pm){
									// total Normal hour
									//echo "FIRST BREAK".$firstBreak."<br />";
									$hours = round(($shiftEnd-$shiftBegin + $adjustTime -$firstBreak )/3600,2);
									if($hours > 8){
										$hours = 8;
									}
									
									$strBegin = date("H:i",$shiftBegin);
									$strEnd = date("H:i",$shiftEnd);
									$strStartStopTime = $strBegin."-".$strEnd;
										
									//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
									if($hours > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
			
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
			
									}
									if($hours > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
			
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
			
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
								}
								if($shiftBegin >=$date6Pm){
			
									$hours = round(($shiftEnd-$shiftBegin + $adjustTime )/3600,2);
									$strBegin = date("H:i",$shiftBegin);
									$strEnd = date("H:i",$shiftEnd);
									$strStartStopTime = $strBegin."-".$strEnd;
										
									//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
									if($hours > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
			
									}
									if($hours > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
			
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
			
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
									//total 6 pm
			
								}
								if($shiftBegin< $date6Pm && $shiftEnd > $date6Pm){
									//before and after
									$hoursNormal = round(($date6Pm-$shiftBegin-$firstBreak)/3600,2);
									$strBegin = date("H:i",$shiftBegin);
									$strEnd = date("H:i",$shiftEnd);
									$strStartStopTime = $strBegin."-".$strEnd;
										
									//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
									if($hoursNormal > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
			
									}
									if($hoursNormal > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
			
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
			
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
									$hoursExt = round(($shiftEnd-$date6Pm)/3600,2);
									echo "Ext Hour is".$hoursExt."|";
								
									if($hoursExt > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
			
									}
									if($hoursExt > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
			
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
								}
			
							}
								
						}//end else
						}
					}
				}
				// sort name s
				
				$arrFileNames = array_unique($arrFileNames,SORT_STRING);
			
				$fileHandler = new Model_Fileshandler();
				$zipFileName = "MYOB_TS_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
				$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);

				$this->view->link = "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
				$this->renderScript("/rosteraudit/payroll-wizard-complete.phtml");
			
			
			
			
		}
		
		//d($arrRes);
	}
	
	/**
	 * when the staff registered it gives default 7 days to submit all the infos
	 * if not , the password will be blocked 
	 * to extend the password expire date 
	 * using this function 
	 * never expire date is 2037 /12/31
	 */
	public function extendPasswordAction(){
		
		$dateToday = Model_DatetimeHelper::dateToday();
		$neverExpire = "2037-12-31";
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stInfo = new Model_DbTable_Roster_Staffinfo();	
		
		if($_POST){
			if(isset($_POST['btn_7days'])){
				
				$dateToExp = Model_DatetimeHelper::adjustDays("add", $_POST['expire_date'], 7);
				$stDetail->updateExpireDate($dateToExp,$_POST['id']);
				$stDetail->UnLockStaff($_POST['id']);
				$stInfo->updateCheckStatus($_POST['id'], 'leave');
				$stInfo->activeStaff($_POST['id']);
			}
			
			if(isset($_POST['btn_14days'])){
				$dateToExp = Model_DatetimeHelper::adjustDays("add", $_POST['expire_date'], 14);
				$stDetail->updateExpireDate($dateToExp,$_POST['id']);	
				$stDetail->UnLockStaff($_POST['id']);
				$stInfo->updateCheckStatus($_POST['id'], 'leave');
				$stInfo->activeStaff($_POST['id']);
			}
			
			if(isset($_POST['btn_never'])){
				$stDetail->updateExpireDate($neverExpire, $_POST['id']);
				$stInfo->activeStaff($_POST['id']);
				$stDetail->UnLockStaff($_POST['id']);
				$stInfo->updateCheckStatus($_POST['id'], 'leave');
				$stInfo->activeStaff($_POST['id']);
			}
			
		}
		
		
		
		
		$expireList = $stDetail->shouldExpire($neverExpire);
		$expListNew = array();
		
		
		foreach($expireList as $key => $v){
			$tmpArr = $v; 
			$stInfoLine = $stInfo->getStaffinfo($v['id']);
			$tmpArr['in_myob'] = false;
			if($stInfoLine){
				if( $stInfoLine['id_package'] == 2 || $stInfoLine['id_package'] == 5){
					if($stInfoLine['id_record_cash']!=0){
						$tmpArr['in_myob'] = true;
					}
					
				}
				else{
					if($stInfoLine['id_record']!=0){
						$tmpArr['in_myob'] = true;
					}
				}
			}
			$expListNew[] = $tmpArr;
		}
		$this->view->expireList = $expListNew;
		//d($this->view->expireList);	
	}
	
	/**
	 * Offline attendance funciton run on 126 
	 * it get all the offline attendance record 
	 * and insert a fake attendance record of ip 0001 
	 * into the attanece table 
	 */
	public function offlineAttendanceAction(){
		
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$do = $this->_getParam("do");
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		$arrRes = array();
		$attn = new Model_DbTable_Roster_Attnrecord(Zend_Registry::get('db_remoteapp'));
			
		foreach(self::$arrShopMaping as $shop => $mapping){
			
			$invPro = Model_Aposinitnew::initAposInvPro($shop);
			
			$invListOn = $invPro->getOfflineOnduty($dateBegin, $dateEnd);
			$invListOff = $invPro->getOfflineOffduty($dateBegin, $dateEnd);
			//d($invListOn,$invListOff);
			$inv = Model_Aposinitnew::initAposInvoice($shop);
			
			$sales = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
			
			foreach($invListOn as $invoiceLine){
				
				//d($invoiceLine);
				// DATE TIME SAL_CODE
				$invDetail = $inv->getInvoice($invoiceLine);
				$salesMan = $sales->getSalesMan($invDetail['SAL_CODE'], $shop);
				$arrRes[$shop][] = array($invoiceLine,date("Y-m-d",strtotime($invDetail['DATE'])),$invDetail['TIME'],$invDetail['SAL_CODE'],"ONDUTY",$salesMan['id_staff'],$invDetail['REF']);

			}
			foreach($invListOff as $invoiceLine){
				$invDetail = $inv->getInvoice($invoiceLine);
				$salesMan = $sales->getSalesMan($invDetail['SAL_CODE'], $shop);
				$arrRes[$shop][] = array($invoiceLine,date("Y-m-d",strtotime($invDetail['DATE'])),$invDetail['TIME'],$invDetail['SAL_CODE'],"OFFDUTY",$salesMan['id_staff'],$invDetail['REF']);				
			
			}
			
		}

		//d($arrRes);	
		$arrCanNot = array();
		$arrInsert = array();
		
		foreach($arrRes as $shop => $invs){
			
			foreach($invs as $detail){
					date_default_timezone_set('Australia/Melbourne');
					
				if($shop == "ADPC" || $shop  =="CLPC" || $shop  =="CLIC" || $shop =="WLIC"){
				
					date_default_timezone_set('Australia/Adelaide');
				}	
				
				$shopHead =  Model_EncryptHelper::sslPassword($shop);
				$ip = '0.0.0.1';
				
				$invTime = date("U",strtotime($detail[1]." ".$detail[2].":00"));
				$onStatus = $attn->createStatusOnDuty();
				$offStatus = $attn->createStatusOffDuty();
				$status= ($detail[4]=="ONDUTY")?$onStatus:$offStatus;
			
				if($detail[5]>0 && trim($detail[6])==""){
					
					if(!$attn->getSuInsertRecord($detail[5], $invTime, $shopHead, $detail[4])){
						
						if($do == "yes"){
							$attn->addRecord($detail[5], $invTime, $ip, $shopHead, $status);
						}
						//$attn->get
							
							
						$arrInsert[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);						
						
					}
					

				
				}
				else{
					
					//$arrCanNot[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);
					
					
					if($detail[5]>0){
						if(!$attn->getSuInsertRecord($detail[5], $invTime, $shopHead, $detail[4])){	
							$arrCanNot[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);
						}
					}
					else{
						
						$arrCanNot[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);
					}
					
				}
			}
			
			
		}
		
		//d($arrInsert,$arrCanNot);
		$this->view->arrInsert = $arrInsert;
		$this->view->arrCanNot = $arrCanNot;
				
		
		if($_POST){
			foreach($_POST['is_select'] as $key => $v){
				
				$shop = $_POST['shop'][$key];
				
				date_default_timezone_set('Australia/Melbourne');
					
				if($shop == "ADPC" || $shop  =="CLPC" || $shop  =="CLIC" || $shop =="WLIC"){
				
					date_default_timezone_set('Australia/Adelaide');
				}
				
				
				$shopHead =  Model_EncryptHelper::sslPassword($shop);
				$ip = '0.0.0.1';
				
				$invTime = date("U",strtotime($_POST['date'][$key]." ".$_POST['time'][$key]));
				$onStatus = $attn->createStatusOnDuty();
				$offStatus = $attn->createStatusOffDuty();
				$status= ($_POST['on_off'][$key]=="ONDUTY")?$onStatus:$offStatus;
				
				$attn->addRecord($_POST['id'][$key], $invTime, $ip, $shopHead, $status);
				
			}
			
			
		}
		
	}
	
	
	/**
	 * this is the page to create Unconfirm Roster for staff to sign
	 */
	public function etlAction(){
		
		Kint::enabled(false);
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$idStaff = $this->_getParam("id");
		$totalPay = $this->_getParam("total");
		$rate = $this->_getParam("rate");
		
		$comm =  $this->_getParam("comm"); 
		$name = $this->_getParam("name");
		$cycle = $this->_getParam("cycle");
		$nick = $this->_getParam('nick');
		$bonusPay = $this->_getParam('bonus');
		$short = $this->_getParam('short');
		
		
		$this->view->comm = base64_decode($comm);
		$this->view->name = base64_decode($name); 
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$year = explode("-",$dateBegin);
		$this->view->year = $year[0];
		$this->view->cycle = $cycle;
		$this->view->total = $totalPay;
		$this->view->idStaff = $idStaff;
		$this->view->nick = base64_decode($nick);
		$this->view->bonus = $bonusPay;
		$this->view->short = $short;
		
		
		
		if($short != 'yes'){
		//var_dump($totalPay,$rate);
		$limits = round(($totalPay - $bonusPay) / $rate,2);
		
		$step = 1;
		
		//$actRate = 10;
		$limitRate = 20;
		
		//$idStaff = 10;
		//$dateBegin = "2014-05-26";
		//$dateEnd = "2014-06-08";
		
		$ts = new Model_DbTable_Roster_Timesheet();
		$tList = $ts->listConfirmedShiftByStaffIdByDate($idStaff, $dateBegin, $dateEnd);
		
		$arrRes = array();
		
		//d($tList);
		
		$totalPay = 0;
		
		foreach($tList as $key => $v){
			date_default_timezone_set("Australia/Melbourne");
			$totalHour = round(($v['confirm_shift_end'] - $v['confirm_shift_begin'] -$v['break_time'])/3600,2);
			if($totalHour > 0){
				$tmpArr = array();
				$date = date("Y-m-d",$v['confirm_shift_begin']);
				$arrRes[$date] = $totalHour;	
			}
			
		}
		

		
		$arr = $arrRes;
		ksort($arr);
		//d($arr);
		arsort($arr,SORT_NUMERIC);
		// total fit nothing todo
		
		$couts = count($arr);
		
		$average = $limits/$couts;
		
		if(array_sum($arr) <= $limits){
			ksort($arr);
			$this->view->arrRes = $arr;
			//echo "Nothing To Do";
		}
		else{
			
			
		$cot = 0;
		$min = 0.1;	
		while(array_sum($arr)>$limits){
		
			reset($arr);
			$key = key($arr);
			if((current($arr)-$step) > $min)
			$arr[$key] = current($arr)- $step ;
			arsort($arr,SORT_NUMERIC);
			
			$cot++;
			if($cot >1000){
				$step = 0.5;
				//$min = 1;
			}
			if($cot >2000){
				$step = 0.25;
				//$min = 0;
			}
			if($cot > 3000){
				
				echo "CAN NOT BE DONE";
				break;
			}
			if($couts > 14){
				echo "CAN NOT BE DONE > 14 Working Days";
				break;
			}
			if($couts == 0){
				echo "CAN NOT BE DONE No Roster";
				break;
			}
		}	
			
		ksort($arr);
		$this->view->arrRes = $arr;
			
		}
		}else{
			$hour = round(($totalPay/$rate),2);
			$this->view->hour = $hour;
		}
		
		
	}
	
	public function eltPrintAction(){
		$log = new Model_Payroll_Etllog();
		$stfInfo = new Model_DbTable_Roster_Staffinfo();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$payRoll = unserialize(PAYROLL_CYCLE_2015);
		
		$cycle = $this->_getParam('cycle');
		
		if($cycle != ""){
			$tmpList = $log->listEtlByCycle($cycle);
		
		$finalList = array();
		foreach ($tmpList as $k => $v){
			$stf = $stfInfo->getStaffinfo($v['id_staff']);
			if(!empty($stf['id_manger_belong'])){
				$managerD = $stfDetail->getDetail($stf['id_manger_belong']);
				$finalList[$managerD['ni']][] = $stf['first_name']." ".$stf['last_name'];
			}else{
				$finalList['Simon'][] = $stf['first_name']." ".$stf['last_name'];
			}
			
		}
		$this->view->list = $finalList;
		$this->view->cycle = $cycle;
		$this->view->dateBegin = $payRoll[$cycle][0];
 		$this->view->dateEnd = $payRoll[$cycle][1];
		}
	}
	
	/**
	 * This is the function to prepare the unconfirm roster 
	 * it need myob export file 
	 * get the file then calculate the etl one by one
	 * then sum the result  give the elt paper for staff to sign
	 * (now already allocate to manager)
	 * then give a list for account to deposit
	 */
	public function etlListingAction(){
		
		
		$folder = getcwd()."/uploads/";
		$fileName = Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("").".csv";
		$expfolder =  getcwd()."/timesheet_export/";
		
		$dateBegin = "";
		$dateEnd = "";
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$log = new Model_Payroll_Etllog();
		
		$arrRes = array();
		if($_POST){
			// upload file 
			if(isset($_POST['btn_file'])){
				if(move_uploaded_file($_FILES['file']['tmp_name'],$fileName)){

					$orgFileName = $_FILES['file']['name'];
					$arrName = explode(".",$orgFileName);
					$arrDate = explode("_",$arrName[0]);
					$exportFile = "export_".$arrName[0].".csv";
					
					
					if(isset($arrDate[1])){
						$dateBegin = trim($arrDate[1]);
					}
					else{
						
						echo '<script language="javascript" >alert("Incorrect Name Format , Should be Pay_yyyy-mm-dd_yyyy-mm-dd.csv , Rename Your file!");</script>';
					}
					if(isset($arrDate[2])){
						$dateEnd = trim($arrDate[2]);
					}
					
					$fl = fopen($fileName,"r");
					$f2 = fopen($expfolder.$exportFile,"w");
					fputcsv($f2,array("Name","BSB","Acc. No.","Amt"));
					while(($lineData = fgetcsv($fl,1024))!=false){
						
						//d($lineData);
						$arrName = explode(',',$lineData[0]);
						$totalAmt = str_replace(array('$',','), '',$lineData[1]);
						$firstName = str_replace("'","''",ucfirst(strtolower(trim(str_replace(' ', '', $arrName[1])))));
						$lastName = str_replace("'","''",ucfirst(strtolower(trim(str_replace(' ', '', $arrName[0]))))); 
						
						//d($totalAmt,$firstName,$lastName);
						$row = $stInfo->searchStaffName($firstName, $lastName);
						if($row){
						
							$nickName = $stDetail->getDetail($row['id_staff']);
							$arrRes[] = array($row['id_staff'],$firstName,$lastName,$row['id_package'],$row['new_rate'],$row['limit_rate'],$totalAmt,$nickName['ni']);
							fputcsv($f2,array($firstName." ".$lastName,'="'.Model_EncryptHelper::getSslPassword($row['bank_bsb']).'"','="'.Model_EncryptHelper::getSslPassword($row['bank_acc_no']).'"',$totalAmt));
						}
						else{
							$arrRes[] = array(0,$firstName,$lastName,'','','',$totalAmt,'');
							fputcsv($f2,array($firstName." ".$lastName,"","",$totalAmt));
						}
						
						
					}
					fclose($fl);
					fclose($f2);
					
					$this->view->download = "<a href=\"http://".WEB_IP."/timesheet_export/{$exportFile}\" >{$exportFile}</a>";
					@unlink($fileName);
				}
				
			}
	
			
			if(isset($_POST['btn_process']) || isset($_POST['btn_test'])){
				
				$arrFiles = array();
				$zipFileName = "0".Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("").".zip";
				$depFile = "D".Model_DatetimeHelper::dateToday("").Model_DatetimeHelper::timeNow("").".csv";
				$flc = fopen($expfolder.$depFile,'a');
				fputcsv($flc,array("Deposit List For ".Model_DatetimeHelper::dateToday()));
				fputcsv($flc,array("Nick Name","Acc. Name","BSB","Acc. No.","Amt","Record"));
				$log = new Model_Payroll_Etllog();
				
				if(!empty($_POST['sel'])){
				foreach($_POST['sel'] as $k => $v){
					if($_POST['id_staff'][$k]!=0 && $_POST['exp_rate'][$k] > 0 ){
						
						$fullName = base64_encode($_POST['first_name'][$k]." ".$_POST['last_name'][$k]);
						$comms = base64_encode($_POST['comm']);
						$totalAmt = trim($_POST['total_amt'][$k]);
						$nick = base64_encode($_POST['first_name'][$k]);
						$bonusAmt = trim($_POST['bonus_amt'][$k]);
						
						$url = "http://".WEB_IP."/rosteraudit/etl/rate/{$_POST['exp_rate'][$k]}/id/{$_POST['id_staff'][$k]}/date_begin/{$_POST['date_begin']}/date_end/{$_POST['date_end']}/total/{$totalAmt}/name/{$fullName}/comm/{$comms}/cycle/{$_POST['cycle_no']}/nick/{$nick}/bonus/{$bonusAmt}";
						
						$res = Model_System_Downloadhelper::downloadUrl($url);
						$fileName = '';
						
						$fileNameImport = '';
						$errorflag = false;
						
						if(strpos($res,"CAN NOT BE DONE")!==false){
							echo "<span style=\"color:#F00;\">NO. :".($k + 1)." CAN NOT BE DONE<br/></span>";
							$fileName =$_POST['last_name'][$k]." ".$_POST['first_name'][$k]." ".$_POST['date_begin']." to ".$_POST['date_end']."-CANNOTBEDONE.html";
							$errorflag = true;
						}elseif(strpos($res,"Warning")!==false){
							echo "<span style=\"color:#F00;\">NO. :".($k + 1)." CAN NOT BE DONE<br/></span>";
							$fileName =$_POST['last_name'][$k]." ".$_POST['first_name'][$k]." ".$_POST['date_begin']." to ".$_POST['date_end']."-WARNING.html";
							$errorflag = true;
						}
						else{
							
							$fileName =$_POST['last_name'][$k]." ".$_POST['first_name'][$k]." ".$_POST['date_begin']." to ".$_POST['date_end'].".html";
							$fileNameImport = $fileName;
							echo "NO. :".($k + 1)." ".$fileName." Created NO ERROR<br />";
							}
							// update Rate into system
							
							$stInfo->upDateExpRate($_POST['id_staff'][$k],$_POST['exp_rate'][$k]);
							
							if(isset($_POST['btn_process'])){
								
							$fl = fopen($expfolder.$fileName,"w");
							fputs($fl,$res);
							fclose($fl);
							// gather bankings 
							$stInfoLine = $stInfo->getStaffinfo($_POST['id_staff'][$k]);
							$stDetailLine = $stDetail->getDetail($_POST['id_staff'][$k]);
							fputcsv($flc,array($stDetailLine['ni'],$_POST['first_name'][$k]." ".$_POST['last_name'][$k],Model_EncryptHelper::getSslPassword($stInfoLine['bank_bsb']),Model_EncryptHelper::getSslPassword($stInfoLine['bank_acc_no']),$totalAmt,'________'));
							if($_POST['cycle_no'] > 0 ){
								$year = substr(trim($_POST['date_begin']),0,4);
								$log->conditionAddLog($_POST['id_staff'][$k],$_POST['cycle_no'],$year,$fileNameImport);
							}
							else{
								
								echo "ERRORR, NO CYCLE , ERROR , NO CYCLE";
								$errorflag = true;
							}
							
							}
							$arrFiles[] = $expfolder.$fileName;
							
							if($errorflag){
								
								$mail = new Model_Emailshandler();
								$mail->sendActionEmail("eco3@phonecollection.com.au","Unconfirmed Roster Generate Error","Unconfirmed Roster Generate Error");
							}
								
					}
					else{
						
						echo "<span style=\"color:#F00;\">NO. :".($k + 1)." IS MISSING INFORMATION<br/></span>";
					}
				}
				}
				
				//if short List
				if(!empty($_POST['short'])){
					foreach($_POST['short'] as $k => $v){
						if($_POST['id_staff'][$k]!=0 && $_POST['exp_rate'][$k] > 0 ){
					
							$fullName = base64_encode($_POST['first_name'][$k]." ".$_POST['last_name'][$k]);
							$comms = base64_encode($_POST['comm']);
							$totalAmt = trim($_POST['total_amt'][$k]);
							$nick = base64_encode($_POST['first_name'][$k]);
							$bonusAmt = trim($_POST['bonus_amt'][$k]);
					
							$url = "http://".WEB_IP."/rosteraudit/etl/rate/{$_POST['exp_rate'][$k]}/id/{$_POST['id_staff'][$k]}/date_begin/{$_POST['date_begin']}/date_end/{$_POST['date_end']}/total/{$totalAmt}/name/{$fullName}/comm/{$comms}/cycle/{$_POST['cycle_no']}/nick/{$nick}/bonus/{$bonusAmt}/short/yes";
					
							$res = Model_System_Downloadhelper::downloadUrl($url);
		
							$fileName =$_POST['last_name'][$k]." ".$_POST['first_name'][$k]." ".$_POST['date_begin']." to ".$_POST['date_end']."-short".".html";
							$fileNameImport = $fileName;
							echo "NO. :".($k + 1)." ".$fileName." Created NO ERROR<br />";
							
							// update Rate into system
								
							$stInfo->upDateExpRate($_POST['id_staff'][$k],$_POST['exp_rate'][$k]);
								
							if(isset($_POST['btn_process'])){
					
								$fl = fopen($expfolder.$fileName,"w");
								fputs($fl,$res);
								fclose($fl);
								// gather bankings
								$stInfoLine = $stInfo->getStaffinfo($_POST['id_staff'][$k]);
								$stDetailLine = $stDetail->getDetail($_POST['id_staff'][$k]);
								fputcsv($flc,array($stDetailLine['ni'],$_POST['first_name'][$k]." ".$_POST['last_name'][$k],Model_EncryptHelper::getSslPassword($stInfoLine['bank_bsb']),Model_EncryptHelper::getSslPassword($stInfoLine['bank_acc_no']),$totalAmt,'________'));
								if($_POST['cycle_no'] > 0 ){
									$year = substr(trim($_POST['date_begin']),0,4);
									$log->conditionAddLog($_POST['id_staff'][$k],$_POST['cycle_no'],$year,$fileNameImport,1);
								}
								else{
					
									echo "ERRORR, NO CYCLE , ERROR , NO CYCLE";
									$errorflag = true;
								}
									
							}
							$arrFiles[] = $expfolder.$fileName;
					
						}
						else{
					
							echo "<span style=\"color:#F00;\">NO. :".($k + 1)." IS MISSING INFORMATION<br/></span>";
						}
					}
				}
				fclose($flc);
				$arrFiles[] = $expfolder.$depFile;
				// finish foreach 
				if(isset($_POST['btn_process'])){
				$fileHandler = new Model_Fileshandler();
				$fileHandler->create_zip($arrFiles,$expfolder.$zipFileName);
				}
			
			}
			
			// actually do the job 
			
			
			
			
		}
		//d($arrRes);
		$this->view->arrRes = $arrRes;
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		// read csv file ,
		// list all people name 
		// search name and find time table 
		// find rate limits
		// give a list 
		
		//if post according the rate and people , produce hour details
		// package and email it 
		// save the rate 
		
	}
	/**
	 * List Changes in This payroll cycle , which is last two weeks , 
	 * @author Norman
	 */
	public function changeSummaryAction(){
		
		$dateEnd = Model_DatetimeHelper::getLastWeekSunday();
		$dateBegin = Model_DatetimeHelper::adjustWeeks("sub",Model_DatetimeHelper::getLastWeekMonday(),1);
		
		
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$typeList = $stInfo->listChanges($dateBegin, $dateEnd,"type");
		$rateList = $stInfo->listChanges($dateBegin, $dateEnd,"rate");
		$leaveList =  $stInfo->listChanges($dateBegin, $dateEnd,"leave");
		
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		$this->view->typeList = $typeList;
		$this->view->rateList = $rateList;
		$this->view->leaveList = $leaveList;
	}
	
	/**
	 * Auto run function for disable leave staff
	 * or no login/Holiday in 21 days staff except new staff
	 @author leo
	 */
	public function autoLeaveAction(){
		
		$dateToCheck = Model_DatetimeHelper::dateYesterday();
		$dateStart = Model_DatetimeHelper::adjustDays('sub', $dateToCheck, 20);
		//$dateToCheck = '2014-08-01';
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attend = new Model_DbTable_Roster_Attnrecord();
		$stLeave = new Model_Hr_Staffleave(); 
		$stLog = new Model_Hr_Traineelog();
		$managerEmail = unserialize(ARR_MANAGER_EMAIL);
		
		$stList = $stInfo->listChanges('2014-07-01', $dateToCheck,"leave");
		$activeList = $stDetail->listAllActiveStaff();
	
		$noAttendList = array();
		/*
		if($stList){
			
			foreach($stList as $key => $v){
				
				if($v['leave'] != 9){
					$idStaff = $v['id_staff'];
				
					$stDetail->disActive($idStaff);
					$stInfo->disActiveStaff($idStaff);
				}
			}
		
		}
		if($activeList){
			foreach ($activeList as $k => $v){

				$attCheck = $attend->listRecordByStaffId($v['id'], $dateStart, $dateToCheck);
			
				if(!$attCheck && $v['id'] != '431' && $v['id'] != '410' && $v['id'] != '110'){
					$leaveCheck = $stLeave->getApproveLeaveByIdPeriod($v['id'], $dateStart, $dateToCheck);
					$stfInfo = $stInfo->getStaffinfo($v['id']);
					if(!$leaveCheck && Model_DatetimeHelper::dateDiff($stfInfo['register_date'], $dateStart) > 21){
						$noAttendList[] = $v;
					}
				}

			}
		}
		foreach ($noAttendList as $k2 => $v2){
			$idStaff = $v2['id'];
			$lastAttDate = $attend->lastDayLogin($idStaff);
			
			$stDetail->disActive($idStaff);
			$stInfo->disActiveStaff($idStaff);
			if($lastAttDate){
				$stInfo->updateLeave($idStaff, 9, $lastAttDate[0]);
		
			}
		}

		*/
		$tranineeList = $stInfo->listAllTrainee();
		$roster = new Model_DbTable_Roster_Timesheet();
		$dateYesterday = Model_DatetimeHelper::adjustDays('sub', Model_DatetimeHelper::dateToday(), 1);
		$overHTrainee = array();
		foreach($tranineeList as $k => $v){
			$stLine = $stDetail->getDetail($v['id_staff']);
			$mgLine = $stDetail->getDetail($v['id_manager_introduce']);
		
			$stfRoster = $roster->listShiftByStaffIdByDate($v['id_staff'], $v['register_date'], $dateYesterday);
			$totalH = 0;
			foreach ($stfRoster as $value){
				$hour = 0;
				$tmphour = round(($value['shift_end'] - $value['shift_begin'])/3600,1);
				if($tmphour >= 9){
					$hour = $tmphour - 1;
				}elseif($tmphour > 5){
					$hour = $tmphour - 0.5;
				}else{
					$hour = $tmphour;
				}
				$totalH += $hour;
			}
			
			if($totalH > 80 && $totalH < 100){
				$overHTrainee['80'][$v['id_manager_introduce']][$v['id_staff']]['name'] = $stLine['ni']."(".Model_EncryptHelper::getSslPassword($stLine['n']).")";
				$overHTrainee['80'][$v['id_manager_introduce']][$v['id_staff']]['expire_date'] = $stLine['expire_date'];
				//$overHTrainee['80'][$v['id_manager_introduce']][$v['id_staff']]['manager'] = $mgLine['ni']."(".Model_EncryptHelper::getSslPassword($mgLine['n']).")";
			}elseif ($totalH >= 100){
				$overHTrainee['100'][$v['id_manager_introduce']][$v['id_staff']]['name'] = $stLine['ni']."(".Model_EncryptHelper::getSslPassword($stLine['n']).")";
				$overHTrainee['100'][$v['id_manager_introduce']][$v['id_staff']]['expire_date'] = $stLine['expire_date'];
				//	$overHTrainee['100'][$v['id_manager_introduce']][$v['id_staff']]['manager'] = $mgLine['ni']."(".Model_EncryptHelper::getSslPassword($mgLine['n']).")";
			}
		}

		$email = new Model_Emailshandler();
		foreach ($overHTrainee as $time => $list){
			
			if(!empty($list)){
				if($time == 80){
					
					foreach ($list as $id => $nameList){
						$body = "Hi Manager<br/> These staff training time is over ".$time." <br/>Please send Performance review to Simon (cc office) in 48 hours to complete training for these staff.<br/><br/>";
						foreach ($nameList as $name){
							$body .= "Staff Name:".$name['name']."<br/>";
						}
						
						$mEmail = $managerEmail[$id];
						$body .= "If you have any problems , please call head office";
						
						//office@phonecollection.com.au;simon.phonecollection@gmail.com
						if($mEmail){
							$email->sendNormalEmail('office@phonecollection.com.au;simon.phonecollection@gmail.com;'.$mEmail, 'Over '.$time.' Hour Trainee List', $body);
						}else{
							$email->sendNormalEmail('office@phonecollection.com.au;simon.phonecollection@gmail.com;eco3@phonecollection.com.au', 'Over '.$time.' Hour Trainee List', $body);
						}
						
						
					}
				
				}
				
				if($time == 100){
					
					foreach ($list as $id => $nameList){
						$body = "Hi Manager<br/> These staff training time is over ".$time." <br/>These Staffs' position has changed into normal staff(KPI/Working hour will be evaluated same as normal staff.<br/>
						Please order uniform for the staff as soon as possible<br/>";
						foreach ($nameList as $stfId => $name){
							$body .= "Staff Name:".$name['name']."<br/>";
							$stInfo->updatePosition($stfId,2);
							
							$mailbody = "Staff ".$name['name'].", ID[".$stfId."] has passed the traning period,the current position is part time.This is just a notice ,you need to do nothing.";
							$mailbodyAcc = "Simon has Pass a new trainee".$name['name'].", ID[".$stfId."], the current position has been changed to part time.";
							$subject = "Trainee Pass Trainning Peroid";
							if($name['expire_date'] != '2037-12-31'){
							
								$newExpDate = Model_DatetimeHelper::adjustYears("add",Model_DatetimeHelper::dateToday(),14);
								$stDetail->updateExpireDate($newExpDate, $stfId);
							
								$mailbodyAcc .= "The staff still did not submit all Paper Document, please double check the document list for the staff, if everything is ready, please go to click 'never expire'";
								$mailbodyAcc .= "Other wise, PLEASE MUST FOLLOW UP THIS CASE.";
								$subject .=",Still Need Document, Please follow Up";
								$email->sendActionEmail("payroll@phonecollection.com.au",$subject,$mailbodyAcc);
							}
							else{
							
								$mailbodyAcc .= "This is just a notice ,you need to do nothing.";
								$email->sendNormalEmail("payroll@phonecollection.com.au",$subject,$mailbodyAcc);
							}
							$stLog->addTraineelog($stfId, $id, Model_DatetimeHelper::dateToday(), Model_DatetimeHelper::dateToday()." ".Model_DatetimeHelper::timeNow(),2);
						}
						$mEmail = $managerEmail[$id];
						$body .= "If you have any problems , please call head office";
						
						//office@phonecollection.com.au;simon.phonecollection@gmail.com
						if($mEmail){
							$email->sendNormalEmail('office@phonecollection.com.au;simon.phonecollection@gmail.com;'.$mEmail, 'Over '.$time.' Hour Trainee List', $body);
						}else{
							$email->sendNormalEmail('office@phonecollection.com.au;simon.phonecollection@gmail.com', 'Over '.$time.' Hour Trainee List', $body);
						}
					}
				}
				
				
			}
		}

	}
	/**
	 * auto lock function prevment any more modification after the roster is confirmed
	 * this funcion run on every payroll monday night 
	 * 
	 */
	public function autoLockAction(){
		$do = $this->_getParam("do");
		if($do == "yes"){
		$intDateToday = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::getThisWeekMonday());
		$ts = new Model_DbTable_Roster_Timesheet();
		$ts->updateLock($intDateToday);
		}
	}
	/**
	 * Main page for entre payroll wizard
	 * need update payroll cycle if change
	 * @version 2014-08-07
	 * @author Leo
	 */
	public function paryrollWizardAction(){
		$payrollDetail = new Model_DbTable_Payrolldetail();
		$currentCycle = $payrollDetail->getlastPayrollCycle();
		$payrollSelect = unserialize(PAYROLL_CYCLE_SELECT);
		$lastcycle = $currentCycle[0]['id_max'];
		$thiscycle = $currentCycle[0]['id_max']+1;
		$cycleKey = $thiscycle;
		$payrollComment = $payrollDetail->getPayrollDetail($lastcycle);
		$this->view->comment = $payrollComment;
		
		
		$currentWeekStart = $payrollSelect[$thiscycle][0];
		$currentWeekEnd = $payrollSelect[$thiscycle][1];
		if($thiscycle > 26){
			$thiscycle = $thiscycle - 26; 
		}
		if($lastcycle > 26){
			$lastcycle = $lastcycle - 26;
		}
		
		$this->view->payroll = $thiscycle;
		$this->view->payroll2 = $lastcycle;

		
		
		if(isset($_POST['next'])){
			
			$this->_redirect('/rosteraudit/payroll-wizard-list-problems/date_begin/'.$currentWeekStart.'/date_end/'.$currentWeekEnd);
		}

		$this->view->dateStart = $currentWeekStart;
		$this->view->dateEnd = $currentWeekEnd;
		
		if(isset($_POST['short_payment'])){
			$this->_redirect('/rosteraudit/payroll-wizard-opening-case/');
		}
		
		if(isset($_POST['confirm'])){

			$dateToday = Model_DatetimeHelper::dateToday();
			$payrollDetail->addPayrollDetail($cycleKey, $dateToday);
			$url = "http://".WEB_IP."/rosteraudit/paryroll-wizard";
			$this->_redirect($url);
		}
		
	}
	
	/**
	 * This function is for check shop confirm roster
	 * if not cannot start payroll wizard
	 @author leo
	 */
	public function payrollWizardListProblemsAction(){
	
		date_default_timezone_set('Australia/Melbourne');
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$atRecord = new Model_DbTable_Roster_Attnrecord();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$arrResult = array();
		
				
			$dateBegin = $this->_getParam("date_begin");
			$dateEnd = $this->_getParam("date_end");
			
			$this->view->dateBegin = $dateBegin;
			$this->view->dateEnd = $dateEnd;
			//$type = $_GET["type"];
			$intDateBegin = Model_DatetimeHelper::tranferToInt($dateBegin);
			$intDateEnd = Model_DatetimeHelper::tranferToInt($dateEnd) + 86400;
			$missingShops = $tSheet->listShiftNotFinish($intDateBegin, $intDateEnd);
			$this->view->missingShops = $missingShops;
				
			//
			$shiftList = $tSheet->listShiftByDate($dateBegin, $dateEnd);
				
			foreach($shiftList as $shift){
			$tmpArr = $shift;
			$idStaff = $shift["id_staff"];
			$shopHead = Model_EncryptHelper::sslPassword($shift["shop_head"]);
					$dateCheck = date("Y-m-d",$shift["shift_begin"]);
	
	
					$attLine = $atRecord->getFirstOnLastOffDuty($idStaff, $dateCheck, $shopHead);
					$tmpArr["on_duty"] = $attLine[0];
					$tmpArr["off_duty"] = $attLine[1];
					$tmpArr["error"] = "";
	
					if($shift["confirm_shift_begin"]!= null && $shift["confirm_shift_end"]!= null){
					//staff shift login match staff actuall login do not match manage , manager did not do change web we can change
							if(
							($shift["confirm_shift_begin"] != $shift["shift_begin"] || $shift["confirm_shift_end"] != $shift["shift_end"])
							&& ($attLine[0]!="" && $attLine[1]!="" )
							&& ($shift["confirm_shift_begin"] != $shift["confirm_shift_end"])
							) {
								
							//$tmpArr["error"] .= "Mgr Assign Diff Time Period,Calculate Base On Mgr,BUT Need Send to Mgr Confirm";
								$tmpArr["error"] = array('<div style="width:120px;; background-color:#FDF7AC">YES,NotMatch</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>');
								$stLine = $stInfo->getStaffinfo($idStaff);
	

							}
						if( $shift["confirm_shift_end"] - $shift["confirm_shift_begin"] >= 34200){
	
							$tmpArr["error"] = array('<div style="width:120px;; background-color:#FDF7AC">Over 9.5 Hour </div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>');
							$stLine = $stInfo->getStaffinfo($idStaff);
	

						}
						//manager do not allocate time , it has the actually login , we can change it
						if(($shift["confirm_shift_begin"] == $shift["confirm_shift_end"]) && ($attLine[0] != "" && $attLine[1]!="")){
	
						//check if all the record is calculated
						//var_dump($idStaff, $shopHead, $dateCheck, $dateCheck);
							$staffShiftList = $tSheet->listAllShiftByStaffIdByDateByShop($idStaff,$shift["shop_head"], $dateCheck, $dateCheck);
							$allEmpty = true;
								
	
							//var_dump($staffShiftList);
										
						if($staffShiftList){
								foreach($staffShiftList as $k2 => $v2){
							
									if($v2["confirm_shift_begin"] != $v2["confirm_shift_end"]){
									$allEmpty = false;
									}
								}
						}
							
							if($allEmpty){
							//$tmpArr["error"] = "Staff Come,But Mgr NOT Allocate,Will NOT Calculate, Need Send to Mgr Confirm";
									$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">NO</div>','<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
									$stLine = $stInfo->getStaffinfo($idStaff);
	

							}
	
						}
							//both manager and staff did not do job well
						if(($shift["confirm_shift_begin"] == $shift["confirm_shift_end"]) && ($attLine[0] == "" || $attLine[1]=="") && ($attLine[0] != $attLine[1])){
	
							$staffShiftList = $tSheet->listAllShiftByStaffIdByDateByShop($idStaff,$shift["shop_head"], $dateCheck, $dateCheck);
							$allEmpty = true;
							//echo "L2:";
								//var_dump($staffShiftList);
								if($staffShiftList){
									foreach($staffShiftList as $k2 => $v2){
								//var_dump($v2);
										if($v2["confirm_shift_begin"] != $v2["confirm_shift_end"]){
										$allEmpty = false;
										}
									}
								}
								if($allEmpty){
								//$tmpArr["error"] = "Mgr NOT Allocate, Staff Also Missing Record, Will Not Calculate, Need Send to Mgr Confirm";
									$tmpArr["error"] = array('<div style="width:120px;; background-color:#FEBCBA">NO</div>','<div style="width:120px;; background-color:#FDF7AC">MAY BE</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
									$stLine = $stInfo->getStaffinfo($idStaff);
									
								}
	
						}
									// staff did not do job well , missing login record
							if(($shift["confirm_shift_begin"] != $shift["confirm_shift_end"]) && ($attLine[0] == "" || $attLine[1]=="")){

								$tmpArr["error"] = array('<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FDF7AC">MAY BE</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
	
									if($attLine[0] == "" && $attLine[1]=="" ){
	
										$tmpArr["error"] = array('<div style="width:120px;; background-color:#AAFFB7">YES</div>','<div style="width:120px;; background-color:#FEBCBA">NO RECORD</div>','<div style="width:120px;; background-color:#FEBCBA">NO</div>');
										
									}
	
									$stLine = $stInfo->getStaffinfo($idStaff);
	
							}
										
									///staff shift login do not match manage allocated, manager allocedat match staff login, staff input wrong time
					}
				}

							$erros = array();
							$stIds = array();
							$dates = array();
	
						foreach($arrResult as $k => $v){
	
							$erros[$k] = $v["error"];
							$stIds[$k] = $v["id_staff"];
							$dates[$k] = $v["confirm_shift_begin"];
						}
	
			array_multisort($stIds,SORT_ASC,$dates,SORT_ASC,$erros,SORT_ASC,$arrResult);
			$this->view->arrResult = $arrResult;
		}
	
	/**
	 * This function is for notice rate/type/leave list base on last 1 year
	 * Non login staff list for current payroll cycle 
	 @author leo
	 */
	public function payrollWizardChangeSummaryAction(){

		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");

		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stfLogin = new Model_DbTable_Roster_Attnrecord();
		$allStaff = $stfDetail->listAllActiveStaff();
		$nonLoginList = array();
		foreach($allStaff as $k => $v){
			if($v['a'] == 1 && $v['id'] != 431 && $v['id'] != 410 && $v['id'] != 110){
				$whCheck = $stInfo->getStaffinfo($v['id']);
				if($whCheck['is_wh'] != 1){
					$loginCheck = $stfLogin->listRecordByStaffId($v['id'], $dateBegin, $dateEnd);

					if(!$loginCheck){
						$nonLoginList[] = $v;
					}
				}
			}
		}
		
		
		$typeList = $stInfo->listChangesUnhandle($dateBegin, $dateEnd,"type");
		$rateList = $stInfo->listChangesUnhandle($dateBegin, $dateEnd,"rate");
		$leaveList =  $stInfo->listChangesUnhandle($dateBegin, $dateEnd,"leave");
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->nonLoginList = $nonLoginList;
		$this->view->typeList = $typeList;
		$this->view->rateList = $rateList;
		$this->view->leaveList = $leaveList;
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;

		if(isset($_POST['next'])){
			
			$changeTypeList = array();
			$changeRateList = array();
			$leaveList = array();
			if($_POST['checksign1']){
				foreach($_POST['checksign1'] as $k1 => $v1){
					$idStaff = $_POST['id_staff1'][$k1];
					$changeTypeList[] = $idStaff;
				}
			}
			if($_POST['checksign2']){
				foreach($_POST['checksign2'] as $k2 => $v2){
					$idStaff = $_POST['id_staff2'][$k2];
					$changeRateList[] = $idStaff;
				}
			}
			if($_POST['checksign3']){
				foreach($_POST['checksign3'] as $k3 => $v3){
					$idStaff = $_POST['id_staff3'][$k3];
					$leaveList[] = $idStaff;
				}
			}
			if($changeTypeList!= null){
				foreach($changeTypeList as $key1 => $val1){
					$stInfo->updateChanges($val1, "type");
				}
			}
			if($changeRateList!= null){
				foreach($changeRateList as $key2 => $val2){
					$stInfo->updateChanges($val2, "rate");
				}
			}
			if($leaveList!= null){
				foreach($leaveList as $key3 => $val3){
					$stInfo->updateChanges($val3, "leave");
				}
			}
			$url = "http://".WEB_IP."/rosteraudit/payroll-wizard-offline-attendance/date_begin/".$dateBegin."/date_end/".$dateEnd."/next/yes";
			$this->_redirect($url);
		}
	}
	
	/**
	 * This function is for show T/R bonus for current payroll
	 * export bonus record for MYOB
	 @author leo
	 */
	public function payrollWizardCalculateBonusAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$stfBonus = new Model_Payroll_Staffbonus();
		$stfDetail = new Model_DbTable_Roster_Staffinfo();
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Notes","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);
		$arrFileNames = array();
		$exportFolder = getcwd()."/export/timesheet/";
		$zipFolder =  getcwd()."/export/timesheetzip/";
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$fullFileName = "FULL_".$dateBegin."-".$dateEnd.".txt";
			$fileName1 = "BE_".$fullFileName;
			$fileName2 = "ACDF_".$fullFileName;
			$exportFolder = getcwd()."/export/timesheet/";
			
			$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Note","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
			$strFileHead = implode("\t",$arrFileHead);
		
			$f2 = fopen($exportFolder.$fileName1,"w");
			fputs($f2,$strFileHead."\r\n");
				
			fclose($f2);

			$f2 = fopen($exportFolder.$fileName2,"w");
			fputs($f2,$strFileHead."\r\n");
			
			fclose($f2);
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
		$list = $stfBonus->exportReleasedStaffMYOB($dateBegin,$dateEnd);
		$cashList = array();
		$bankList = array();
		$cashSort = array();
		$bankSort = array();
		foreach($list as $k2 => $v2){
			$tmpArr = array();
	
			if($v2['pay_type'] == 1){
				$tmpArr['id_staff'] = $v2['id_staff'];
				$tmpArr['id_bonus'] = $v2['id_bonus'];
				$tmpArr['type_bonus'] = $v2['type_bonus'];
				$tmpArr['amt_total_bonus'] = $v2['amt_total_bonus'];
				$tmpArr['period_bonus_begin'] = $v2['period_bonus_begin'];
				$tmpArr['Period_bonus_end'] = $v2['Period_bonus_end'];
				$tmpArr['payment_status'] = $v2['payment_status'];
				$tmpArr['pay_date'] = $v2['pay_date'];
				$cashList[] = $tmpArr;
				$cashSort[] = $v2['id_bonus'];
			}
			if($v2['pay_type'] == 2){
				$tmpArr['id_staff'] = $v2['id_staff'];
				$tmpArr['id_bonus'] = $v2['id_bonus'];
				$tmpArr['type_bonus'] = $v2['type_bonus'];
				$tmpArr['amt_total_bonus'] = $v2['amt_total_bonus'];
				$tmpArr['amt_bank_bonus'] = $v2['amt_bank_bonus'];
				$tmpArr['amt_bonus_super'] = $v2['amt_bonus_super'];
				$tmpArr['period_bonus_begin'] = $v2['period_bonus_begin'];
				$tmpArr['Period_bonus_end'] = $v2['Period_bonus_end'];
				$tmpArr['payment_status'] = $v2['payment_status'];
				$tmpArr['pay_date'] = $v2['pay_date'];
				$bankList[] = $tmpArr;
				$bankSort[] = $v2['id_bonus'];
			}
		}
		array_multisort($cashSort,SORT_ASC,$cashList);
		array_multisort($bankSort,SORT_ASC,$bankList);
 		$this->view->cashList = $cashList;
		$this->view->bankList = $bankList;

		if(isset($_POST['export_file'])){

			$arrTmp = $stfBonus->exportReleasedStaffMYOB($dateBegin,$dateEnd);
			$sort = array();
			$arrStfBonus = array();
			foreach($arrTmp as $k3 => $v3){
				$sort[] = $v3['id_bonus'];
				$arrStfBonus[] = $v3;
			}
			array_multisort($sort,$arrStfBonus);
			$orgFileName = "BONUS_".$dateBegin."-".$dateEnd.".txt";
			$fullFileName = "FULL_".$dateBegin."-".$dateEnd.".txt";
			foreach($arrFileNameStr as $key => $value){
				if($value!=""){
					$fileName = $value.$orgFileName;
					$fileName2 = $value.$fullFileName;
					$strFileHead = implode("\t",$arrFileHead);
					$fl = fopen($exportFolder.$fileName,"w");
					$f2 = fopen($exportFolder.$fileName2,"w");
					fputs($fl,$strFileHead."\r\n");
					fputs($f2,$strFileHead."\r\n");
					fclose($fl);
					fclose($f2);
			
				}
			}
			$cash = 0;
			$bank = 0;
			foreach($arrStfBonus as $k => $v){
				if($v['payment_status']!= 'yes'){
					$stInfoLine = $stfDetail->getStaffinfo($v['id_staff']);
					$firstName = $stInfoLine["first_name"];
					$lastName = $stInfoLine["last_name"];
					$cardID = $stInfoLine["id_card"];
					
					$activeStaff = $stInfoLine["active_staff"];
					$idPackage = $stInfoLine["id_package"];
					$strDate = date("j/m/Y",strtotime($dateEnd));
					
					
					if($idPackage == 1 || $idPackage == 3 || $idPackage == 4 || $idPackage == 6 || $idPackage == 7 || $idPackage == 8){
						$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
						$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
						$recordID =  $stInfoLine["id_record"];
						if($v['type_bonus'] == 3){
							$arrTmp = array($lastName,$firstName,'T Bonus',$v['detail_bonus'],$strDate,$v['amt_bank_bonus'],'0000-00-00',$cardID,$recordID);
						}
						if($v['type_bonus'] == 1){
							$arrTmp = array($lastName,$firstName,'R Bonus',$v['detail_bonus'],$strDate,$v['amt_bank_bonus'],'0000-00-00',$cardID,$recordID);
						}
						$bank++;
					}
					if($idPackage == 2 || $idPackage == 5){
						$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
						$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
						$recordID =  $stInfoLine["id_record_cash"];
						if($v['type_bonus'] == 3){
							$arrTmp = array($lastName,$firstName,'T Bonus',$v['detail_bonus'],$strDate,$v['amt_cash_bonus'],'0000-00-00',$cardID,$recordID);
						}
						if($v['type_bonus'] == 1){
							$arrTmp = array($lastName,$firstName,'R Bonus',$v['detail_bonus'],$strDate,$v['amt_cash_bonus'],'0000-00-00',$cardID,$recordID);
						}
						$cash++;
					}
					
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fputs($f2,$strTmp."\r\n");
					fclose($fl);
					fclose($f2);
					$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
					$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
					
				}
			}
			$arrFileNames = array_unique($arrFileNames,SORT_STRING);
			
			$fileHandler = new Model_Fileshandler();
			$zipFileName = "MYOB_BONUS_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
			$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);
			
			$this->view->cashList = $cashList;
			$this->view->bankList = $bankList;
			$this->view->cashCount = $cash;
			$this->view->bankCount = $bank;
			$this->view->link = "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
		}
	}
	
	
	public function payrollWizardPreOfflineAttendanceAction(){
		$offlineCase = new Model_DbTable_Roster_Offlinecaserecord(Zend_Registry::get('db_remoteapp'));
		$attn = new Model_DbTable_Roster_Attnrecord(Zend_Registry::get('db_remoteapp'));
		$dateToday = Model_DatetimeHelper::dateToday();
		$dateBefore = Model_DatetimeHelper::adjustDays('sub', $dateToday, 3);

		foreach(self::$arrShopMaping as $shop => $mapping){
			date_default_timezone_set('Australia/Melbourne');
				
			if($shop == "ADPC" || $shop  =="CLPC" || $shop  =="CLIC" || $shop =="WLIC"){
			
				date_default_timezone_set('Australia/Adelaide');
			}
				
			$invPro = Model_Aposinitnew::initAposInvPro($shop);
				
			$invListOn = $invPro->getOfflineOnduty($dateBefore, $dateToday);
			$invListOff = $invPro->getOfflineOffduty($dateBefore, $dateToday);
			//d($invListOn,$invListOff);
			$inv = Model_Aposinitnew::initAposInvoice($shop);
				
			$sales = new Model_DbTable_Roster_Salesmandetail(Zend_Registry::get('db_remoteapp'));
				
			foreach($invListOn as $invoiceLine){
		
				//d($invoiceLine);
				// DATE TIME SAL_CODE
				$invDetail = $inv->getInvoice($invoiceLine);
				$salesMan = $sales->getSalesMan($invDetail['SAL_CODE'], $shop);
				$arrRes[$shop][] = array($invoiceLine,date("Y-m-d",strtotime($invDetail['DATE'])),$invDetail['TIME'],$invDetail['SAL_CODE'],"ONDUTY",$salesMan['id_staff'],$invDetail['REF']);
		
			}
			foreach($invListOff as $invoiceLine){
				$invDetail = $inv->getInvoice($invoiceLine);
				$salesMan = $sales->getSalesMan($invDetail['SAL_CODE'], $shop);
				$arrRes[$shop][] = array($invoiceLine,date("Y-m-d",strtotime($invDetail['DATE'])),$invDetail['TIME'],$invDetail['SAL_CODE'],"OFFDUTY",$salesMan['id_staff'],$invDetail['REF']);
					
			}
				
		}
		
		
		$arrCanNot = array();
		$arrInsert = array();
		if(!empty($arrRes)){
		foreach($arrRes as $shop => $invs){
				
			foreach($invs as $detail){
				date_default_timezone_set('Australia/Melbourne');
					
				if($shop == "ADPC" || $shop  =="CLPC" || $shop  =="CLIC" || $shop =="WLIC"){
		
					date_default_timezone_set('Australia/Adelaide');
				}
		
				$shopHead =  Model_EncryptHelper::sslPassword($shop);
				$ip = '0.0.0.1';
		
				$invTime = date("U",strtotime($detail[1]." ".$detail[2].":00"));
				$onStatus = $attn->createStatusOnDuty();
				$offStatus = $attn->createStatusOffDuty();
				$status= ($detail[4]=="ONDUTY")?$onStatus:$offStatus;
				$stfId = (explode("-", $detail[3]));
				if($detail[5]>0 && trim($detail[6])==""){
						
					if(!$attn->getSuInsertRecord($detail[5], $invTime, $shopHead, $detail[4])){
						//$attn->get
							
							
						$arrInsert[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);
		
					}
						
		
		
				}elseif(is_numeric($stfId[0]) && trim($detail[6])=="" && $stfId[0] != 0){
					if(!$attn->getSuInsertRecord($stfId[0], $invTime, $shopHead, $detail[4])){
						$arrInsert[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$stfId[0],$detail[6]);
					}
				}
				else{

					if($detail[5]>0){
						if(!$attn->getSuInsertRecord($detail[5], $invTime, $shopHead, $detail[4])){
							$arrCanNot[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);
						}
					}
					else{
		
						$arrCanNot[] = array($shop,$detail[0],$detail[1],$detail[2],$detail[3],$detail[4],$detail[5],$detail[6]);
					}
						
				}
			}
				
				
		}
		}

		foreach ($arrInsert as $k2 => $v2){
			$result = $offlineCase->getRecord($v2[0], $v2[1]);
			if(!$result){
				$offlineCase->addRecord($v2[0], $v2[1], $v2[2], $v2[3], $v2[4], $v2[5],$v2[7],1);
					
			}
		}
		
		
		foreach ($arrCanNot as $k2 => $v2){
			$result = $offlineCase->getRecord($v2[0], $v2[1]);
			if(!$result){
				$offlineCase->addRecord($v2[0], $v2[1], $v2[2], $v2[3], $v2[4], $v2[5],$v2[7]);
					
			}
		}
		
		$email = new Model_Emailshandler();
		$email->sendNormalEmail('eco3@phonecollection.com.au', 'Pre-offline', 'pre-offline success');
	}
	
	
	/**
	 * This function is for show allowance for current payroll
	 * export allowance record for MYOB
	 * currently not in use because rule is not clear
	 @author leo
	 */
	public function payrollWizardCalculateAllowanceAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$bonuscycle = unserialize(BONUS_CYCLE_2015);
		$payrollCycle = unserialize(PAYROLL_CYCLE_2015);
		$stfDetail = new Model_DbTable_Roster_Staffinfo();
		$stfAllowance = new Model_Payroll_Staffallowance();
		$allowanceType = unserialize(ALLOWANCE_TYPE);
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Notes","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);
		$arrFileNames = array();
		$exportFolder = getcwd()."/export/timesheet/";
		$zipFolder =  getcwd()."/export/timesheetzip/";
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$this->view->cycle = $bonuscycle;
		foreach($payrollCycle as $k3 => $v3){
			if($dateEnd >= $v3[0] && $dateEnd <= $v3[1]){
				$payrollCycleKey = $k3;
			}
		}
		
		
		$list = $stfAllowance->getAllowanceByPeriod($dateBegin,$dateEnd);
		$sort = array();

		foreach($list as $k2 => $v2){
				$sort[] = $v2['staff_id'];
		}
		array_multisort($sort,SORT_ASC,$list);
		$this->view->allowanceList = $list;
		
		if(isset($_POST['export_file'])){
			
			$orgFileName = "ALLOWANCE_".$dateBegin."-".$dateEnd.".txt";
			$fullFileName = "FULL_".$dateBegin."-".$dateEnd.".txt";
			foreach($arrFileNameStr as $key => $value){
				if($value!=""){
					$fileName = $value.$orgFileName;
					$strFileHead = implode("\t",$arrFileHead);
					$fl = fopen($exportFolder.$fileName,"w");
					fputs($fl,$strFileHead."\r\n");
					fclose($fl);
						
				}
			}
			$cash = 0;
			$bank = 0;
			
			foreach($list as $k => $v){
					
					$stInfoLine = $stfDetail->getStaffinfo($v['staff_id']);
					$firstName = $stInfoLine["first_name"];
					$lastName = $stInfoLine["last_name"];
					$cardID = $stInfoLine["id_card"];
						
					$activeStaff = $stInfoLine["active_staff"];
					$idPackage = $stInfoLine["id_package"];
					$strDate = date("j/m/Y",strtotime($dateEnd));
						
					
					if($idPackage == 1 || $idPackage == 3 || $idPackage == 4 || $idPackage == 6){
						$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
						$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
						$recordID =  $stInfoLine["id_record"];
						$arrTmp = array($lastName,$firstName,'ALLOWANCE',$allowanceType[$v['allowance_type']][1],$strDate,$v['allowance_amount'],'0000-00-00',$cardID,$recordID);
			
						$bank++;
					}
					if($idPackage == 2 || $idPackage == 5){
						$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
						$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
						$recordID =  $stInfoLine["id_record_cash"];
						$arrTmp = array($lastName,$firstName,'ALLOWANCE',$allowanceType[$v['allowance_type']][1],$strDate,$v['allowance_amount'],'0000-00-00',$cardID,$recordID);
						$cash++;
					}
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fputs($f2,$strTmp."\r\n");
					
					fclose($fl);
					fclose($f2);
					
					$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
					$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
					$nextPayDate = $payrollCycleKey + $v['pay_cycle_gap'];
					$stfAllowance->updatePayDate($v['id'], $payrollCycle[$nextPayDate][1]);
					
				
			}
			$arrFileNames = array_unique($arrFileNames,SORT_STRING);
				
			$fileHandler = new Model_Fileshandler();
			$zipFileName = "MYOB_ALLOWANCE_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
			$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);

			$this->view->cashCount = $cash;
			$this->view->bankCount = $bank;
			$this->view->allowanceList = $list;
			$this->view->link = "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
		}
	}
	
	/**
	 * This function is for show holiday leave current payroll
	 *
	 @author leo
	 */
	public function payrollWizardCalculateLeaveAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$leave = new Model_Hr_Staffleave();
		$leaveType = unserialize(LEAVE_TYPE);
		
		$orgFileName = "LEAVE_".$dateBegin."-".$dateEnd.".txt";
		//$fullFileName = "FULL_".$dateBegin."-".$dateEnd.".txt";
		
		$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
		
		$arrLeaveList = array();
		
		
		foreach($arrDate as $dateCheck){
				$arrShift = $tSheet->listShiftByDate($dateCheck, $dateCheck);
				
				//var_dump($arrShift);
				//get 6 pm that date
				foreach($arrShift as $k => $v){
					$arrTmp2 = array();
					$errorFlag = 0;
						
					$staffID = $v["id_staff"];
					$shopHead = $v["shop_head"];
					$attLine = $attRecord->getFirstOnLastOffDuty($staffID, $dateCheck,Model_EncryptHelper::sslPassword($shopHead));
					$stLine = $stDetail->getDetail($staffID);
					$stInfoLine = $stInfo->getStaffinfo($staffID);
						
					if($stLine && $stInfoLine['is_wh'] != 1){

						//staff Name
						$statusLine = $dateCheck.", for ".$stLine["ni"]."-".Model_EncryptHelper::getSslPassword($stLine["n"]);
		
						$fullName = explode(" ",Model_EncryptHelper::getSslPassword($stLine["n"]));
		
						$errorPerson = true;
		
						$firstName = $fullName[0];
						$lastName = $fullName[1];
						$cardID = ucwords(Model_EncryptHelper::getSslPassword($stLine["n"]));
						$recordID = "000";
						$activeStaff = -1;
						$idPackage = 5;

						if($stInfoLine){
								
							$firstName = $stInfoLine["first_name"];
							$lastName = $stInfoLine["last_name"];
							$cardID = $stInfoLine["id_card"];
								
							$activeStaff = $stInfoLine["active_staff"];
							if($stInfoLine["id_package"]){
								$idPackage = $stInfoLine["id_package"];
							}else{
								$idPackage = 5;
							}
								
							$recordID =  $stInfoLine["id_record"];
								
							if($idPackage == 2 || $idPackage == 5){
								$recordID =  $stInfoLine["id_record_cash"];
							}
								
								
						}
						// Export leave time sheet
						
						if($v['holiday_check'] == 1){
							
							$strDate = date("j/m/Y",strtotime($dateCheck));
							$date = date("Y-m-j",strtotime($dateCheck));
							$hours = round(($v['shift_end'] - $v['shift_begin'])/3600,2);
							if($hours > 8){
								$hours = 8;
							}
							$strStartStopTime = date("H:i",$v['shift_begin'])."-".date("H:i",$v['shift_end']);
							$afterFix = "[S]".date("H:i",$v['shift_begin'])."-".date("H:i",$v['shift_end'])."[B]0";
							
							$arrTmp = array($lastName,$firstName,'Holiday Pay',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
						
							$strTmp = implode("\t",$arrTmp);
							
							$leaveDetail = $leave->getApproveLeaveByIdDate($stLine['id'], $date);
							
							
							$arrTmp2['staff_id'] = $stLine['id'];
							$arrTmp2['first_name'] = $firstName;
							$arrTmp2['last_name'] = $lastName;
							$arrTmp2['ni'] = $stLine['ni'];
							$arrTmp2['leave_date'] = $date;
							$arrTmp2['leave_date2'] = $strDate;
							$arrTmp2['leave_type'] = $leaveType[$leaveDetail['period_type']];
							$arrTmp2['hour'] = $hours;
							$arrTmp2['time_begin'] = date("H:i",$v['shift_begin']);
							$arrTmp2['time_end'] = date("H:i",$v['shift_end']);
							$arrTmp2['card_id'] = $cardID;
							$arrTmp2['record_id'] = $recordID;
							$arrTmp2['id_package'] = $idPackage;
							
							
							$arrLeaveList[] = $arrTmp2;
							
		
						}
					}
				}
		}
		$this->view->dateBegin = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$this->view->leaveList = $arrLeaveList;
		//d($arrLeaveList);
		
		if(isset($_POST['export_file'])){
			$arrFileNameStr = unserialize(PAY_FILE_TYPE);
			$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Notes","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
			$exportFolder = getcwd()."/export/timesheet/";
			$zipFolder =  getcwd()."/export/timesheetzip/";
			
			foreach($arrFileNameStr as $key => $value){
				if($value!=""){
					$fileName = $value.$orgFileName;
					$strFileHead = implode("\t",$arrFileHead);
					$fl = fopen($exportFolder.$fileName,"w");
					fputs($fl,$strFileHead."\r\n");
					fclose($fl);
						
				}
			}
			
			
			foreach($arrLeaveList as $k2 => $v2){
					$fl = fopen($exportFolder.$arrFileNameStr[$v2['id_package']].$orgFileName,"a");
					//$f2 = fopen($exportFolder.$arrFileNameStr[$v2['id_package']].$fullFileName,"a");
					$strStartStopTime = $v2['time_begin']."-".$v2['time_end'];
					$afterFix = "[S]".$v2['time_begin']."-".$v2['time_end']."[B]0";
					
					$arrTmp = array($v2['last_name'],$v2['first_name'],'ANNUAL LEAVE',$v2['leave_type'],$v2['leave_date2'],$v2['hour'],$strStartStopTime.$afterFix,$v2['card_id'],$v2['record_id']);
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
					//fputs($f2,$strTmp."\r\n");
					//fclose($f2);
					$arrFileNames[] = $exportFolder.$arrFileNameStr[$v2['id_package']].$orgFileName;
					//$arrFileNames[] = $exportFolder.$arrFileNameStr[$v2['id_package']].$fullFileName;
			}
			$arrFileNames = array_unique($arrFileNames,SORT_STRING);
				
			$fileHandler = new Model_Fileshandler();
			$zipFileName = "MYOB_LEAVE_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
			$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);

			$this->view->link = "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
		}
		
	}
	/**
	 * This function is for handle offline attendance case
	 * add fake attend record
	 @author leo
	 */
	public function payrollWizardOfflineAttendanceAction(){
		date_default_timezone_set('Australia/Melbourne');
		$attCase = new Model_DbTable_Roster_Attncase();
		$offlineCase = new Model_DbTable_Roster_Offlinecaserecord();
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd = $this->_getParam("date_end");
		$nextCheck = $this->_getParam("next");
		$do = "";
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		$attn = new Model_DbTable_Roster_Attnrecord();
		$arrCanNot = array();
		$arrInsert = array();
		$arrRes = array();
		

		$arrRes = $offlineCase->listPeriodUnfinishRecord($dateBegin, $dateEnd);
		foreach ($arrRes as $k => $v){
			if(!$v['will_insert']){
				$arrCanNot[] = $v;
			}else{
				$arrInsert[] = $v;
			}
		}
		
		

		//d($arrInsert);
		
		//d($arrInsert,$arrCanNot);
		if(isset($_POST['submit'])){
			//d($_POST['is_select']);
			foreach($_POST['is_select'] as $key => $v){
				
				$shop = $_POST['shop'][$key];
				
				
					
				if($shop == "ADPC" || $shop  =="CLPC" || $shop  =="CLIC" || $shop =="WLIC"){
				
					date_default_timezone_set('Australia/Adelaide');
				}else{
					date_default_timezone_set('Australia/Melbourne');
				}
				
				
				$shopHead =  Model_EncryptHelper::sslPassword($shop);
				$ip = '0.0.0.1';
				
				$invTime = date("U",strtotime($_POST['date'][$key].$_POST['time'][$key]));

				$onStatus = $attn->createStatusOnDuty();
				$offStatus = $attn->createStatusOffDuty();
				$status= ($_POST['on_off'][$key]=="ONDUTY")?$onStatus:$offStatus;
	
				
				
				$case = $attCase->getUndecideCaseByIDDate($_POST['id'][$key], $_POST['date'][$key]);
	
				if(!empty($case)){
					$attCase->deleteAttncase($case['id_case']);
				}
				$attn->addRecord($_POST['id'][$key], $invTime, $ip, $shopHead, $status);
				$offlineCase->updateRecordResult($key, $_POST['id'][$key], 1);
				
			}
			
			
			foreach ($arrInsert as $k => $v){
				$stfId = (explode("-", $v['staff']));
				$shopHead = Model_EncryptHelper::sslPassword($v['shop']);
				$ip = '0.0.0.1';
				if($v['shop'] == "ADPC" || $v['shop']  =="CLPC" || $v['shop']  =="CLIC" || $v['shop'] =="WLIC"){
				
					date_default_timezone_set('Australia/Adelaide');
				}else{
					date_default_timezone_set('Australia/Melbourne');
				}
				
				$invTime = date("U",strtotime($v['date']." ".$v['time']));
				$case = $attCase->getUndecideCaseByIDDate($stfId[0], $v['date']);
				if(!empty($case)){
					$attCase->deleteAttncase($case['id_case']);
				}
		
				$onStatus = $attn->createStatusOnDuty();
				$offStatus = $attn->createStatusOffDuty();
				$status= ($v['on_off_duty']=="ONDUTY")?$onStatus:$offStatus;
				/*
				if($v['shop'] == 'CLPC' || $v['shop'] == 'ADPC' || $v['shop'] == 'WLIC' || $v['shop'] == 'CLIC'){
					$invTime = $invTime + 1800;
				}*/

				$offlineCase->updateRecordResult($v['id'], $stfId[0], 1);
				$attn->addRecord($stfId[0], $invTime, $ip, $shopHead, $status);
			}
			
			$url = "http://".WEB_IP."/rosteraudit/payroll-wizard-offline-attendance/date_begin/".$dateBegin."/date_end/".$dateEnd."/next/yes";
			$this->_redirect($url);
		}
		$this->view->arrInsert = $arrInsert;
		$this->view->arrCanNot = $arrCanNot;
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		
	}
	
	/**
	 * This function is WH payroll wizard main page
	 */
	public function payrollWizardHqAction(){
		$staffInfo = new Model_DbTable_Roster_Staffinfo();
		$attSheet  = new Model_DbTable_Roster_Timesheet();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		$dateBegin = $this->_getParam("date_begin");
		$datefinish= $this->_getParam("date_end");
		if($dateBegin && $datefinish){
			$this->view->dateStart = $dateBegin;
			$this->view->dateEnd   = $datefinish;
			
			$tmpList   = $staffInfo->listAll();
			$whStaffList = array();
			foreach($tmpList as $k => $v){
				if($v['position_status']== 8 || $v['is_wh'] ==1){
					$whStaffList [] = $v;
				}
			}
			
			$datearray = Model_DatetimeHelper::createDateArray($dateBegin, $datefinish);
			$resArr = array();
			foreach($whStaffList as $k3 => $v3){
				foreach($datearray as $datecheck){
			
					$actList = $attRecord->getFirstOnLastOffDuty($v3['id_staff'], $datecheck, 'QLJw5KUijVObUW1J8Vn3dw==');
					$tList = $attSheet->listShiftByStaffIdByDateByShop($v3['id_staff'],'WHPC',$datecheck,$datecheck);
					if($tList){
						$arrTmp["shift_begin"] = $tList["shift_begin"];//time sheet start
						$arrTmp["shift_end"]=$tList["shift_end"];	//time sheet end
					}
					else{
						$arrTmp["shift_begin"] = "";//time sheet start
						$arrTmp["shift_end"]= "";	//time sheet end
					}
					$arrTmp["act_begin"]=$actList[0];//act start
					$arrTmp["act_end"]=$actList[1];//act end
					$arrTmp["fake_act_begin"] = $actList[2]; // manul inserted begin
					$arrTmp["fake_act_end"] = $actList[3]; // manul inserted end
					if(count($actList)> 4){
						$arrTmp["offline_begin"]=$actList[4];
					}else{
						$arrTmp["offline_begin"]=false;
					}
					if(count($actList)>5){
						$arrTmp["offline_end"]=$actList[5];
					}else{
						$arrTmp["offline_end"]=false;
					}
					//compare status
					$arrTmp["status_begin"] = $attRecord->compareStartTime($arrTmp["shift_begin"], $arrTmp["act_begin"]);
					$arrTmp["status_end"] = $attRecord->compareFinishTime($arrTmp["shift_begin"], $arrTmp["act_begin"]);
						
					if(($tList["shift_begin"]!=null && $actList[0]== null && $tList['holiday_check'] != 1) || ($tList["shift_end"]!=null && $actList[1] == null && $tList['holiday_check'] != 1)){
						$resArr[$v3['id_staff']][$datecheck] = $arrTmp;
					}
				}
			
			}
			$this->view->check = 'Confirmed';
			$this->view->attend = $resArr;
			
			
		}
		if(isset($_POST['confirm_roster'])){
			$dateStart = $_POST['date_begin'];
			$dateEnd   = $_POST['date_end'];
			$tmpList   = $staffInfo->listAll();
			$whStaffList = array();
			foreach($tmpList as $k => $v){
				if($v['position_status']== 8 || $v['is_wh'] ==1){
					$whStaffList [] = $v;
				}
			}
			foreach($whStaffList as $k2 => $v2){
				$timeSheet = $attSheet->listShiftByStaffIdByDate2($v2['id_staff'],$dateStart,$dateEnd);
				if($timeSheet != null){
					foreach($timeSheet as $k3 => $v3){
						if($v3['confirm_shift_begin']==null||$v3['confirm_shift_end']==null){
							$attSheet->updateWhTimeSheet($v3['id_sheet'], $v3['shift_begin'], $v3['shift_end']);
						}
					}
				}
			}
			$this->view->dateStart = $dateStart;
			$this->view->dateEnd   = $dateEnd;
			

			$url = '/rosteraudit/payroll-wizard-hq/date_begin/'.$dateStart.'/date_end/'.$dateEnd;
			$this->_redirect($url);
		}
		
		if(isset($_POST['next'])){
			
			$dateBegin = $this->_getParam("date_begin");
			$datefinish= $this->_getParam("date_end");

			$dateStart = $_POST['date_begin'];
			$dateEnd   = $_POST['date_end'];
			if($dateBegin && $datefinish){
				$url = '/rosteraudit/payroll-wizard-hq-change-summary/date_begin/'.$dateBegin.'/date_end/'.$datefinish;
				$this->_redirect($url);
			}else{
				$url = '/rosteraudit/payroll-wizard-hq-change-summary/date_begin/'.$dateStart.'/date_end/'.$dateEnd;
				$this->_redirect($url);
			}
		}
		
		if(isset($_POST['export_whch'])){
			$dateStart = $_POST['date_begin'];
			$dateEnd   = $_POST['date_end'];
			
			$tmpList   = $staffInfo->listAll();
			$whchList = array();
			foreach($tmpList as $k => $v){
				if($v['is_wh'] ==2){
					$whchList [] = $v;
				}
			}
			foreach($whchList as $k2 => $v2){
				$timeSheet = $attSheet->listShiftByStaffIdByDate2($v2['id_staff'],$dateStart,$dateEnd);
				if($timeSheet != null){
					foreach($timeSheet as $k3 => $v3){
						if($v3['confirm_shift_begin']==null||$v3['confirm_shift_end']==null){
							$attSheet->updateWhTimeSheet($v3['id_sheet'], $v3['shift_begin'], $v3['shift_end']);
						}
					}
				}
			}
			
			$datearray = Model_DatetimeHelper::createDateArray($dateStart, $dateEnd);
			$resArr = array();
			foreach($whchList as $k3 => $v3){
				foreach($datearray as $datecheck){
			
					$actList = $attRecord->getFirstOnLastOffDuty($v3['id_staff'], $datecheck, 'IvkDKPGMh0Xy0gNFZ8KRgA==');
					$tList = $attSheet->listShiftByStaffIdByDateByShop($v3['id_staff'],'WHCH',$datecheck,$datecheck);
					if($tList){
						$arrTmp["shift_begin"] = $tList["shift_begin"];//time sheet start
						$arrTmp["shift_end"]=$tList["shift_end"];	//time sheet end
					}
					else{
						$arrTmp["shift_begin"] = "";//time sheet start
						$arrTmp["shift_end"]= "";	//time sheet end
					}
					
					if($actList[0]){
						$arrTmp["act_begin"]=$actList[0]-3600*3;//act start
					}else{
						$arrTmp["act_begin"]="";
					}
					
					if($actList[1]){
						$arrTmp["act_end"]=$actList[1]- 3600*3;//act end
					}else{
						$arrTmp["act_end"] = "";
					}
					$arrTmp["fake_act_begin"] = $actList[2]; // manul inserted begin
					$arrTmp["fake_act_end"] = $actList[3]; // manul inserted end
					if(count($actList)> 4){
						$arrTmp["offline_begin"]=$actList[4];
					}else{
						$arrTmp["offline_begin"]=false;
					}
					if(count($actList)>5){
						$arrTmp["offline_end"]=$actList[5];
					}else{
						$arrTmp["offline_end"]=false;
					}
					//compare status
					$arrTmp["status_begin"] = $attRecord->compareStartTime($arrTmp["shift_begin"], $arrTmp["act_begin"]);
					$arrTmp["status_end"] = $attRecord->compareFinishTime($arrTmp["shift_begin"], $arrTmp["act_begin"]);
						
					if(($tList["shift_begin"]!=null && $actList[0]== null) || ($tList["shift_end"]!=null && $actList[1] == null)){
						$resArr[$v3['id_staff']][$datecheck] = $arrTmp;
					}
				}
			
			}
			$this->view->attend = $resArr;


			/*
			foreach($whchList as $k2 => $v2){
					$idStaff = $v2['id_staff'];
					$cashStaff[] = $idStaff;
			}
			
			date_default_timezone_set('Asia/Shanghai');
			$TodayDate = date('Y-m-d', time());
				
			$arrPublicHoliday = unserialize(VIC_PUBLIC_HOLIDAY);
			$arrPublicHolidaySa = unserialize(SA_PUBLIC_HOLIDAY);
			$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
			//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Start/Stop Time","Emp. Record ID");
			$arrPayment = array(
					0 => array(),
					1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
					2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
					5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
					6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
			);
			$arrFileNameStr = unserialize(PAY_FILE_TYPE);
				
			$tSheet = new Model_DbTable_Roster_Timesheet();
			$stInfo = new Model_DbTable_Roster_Staffinfo();
			$stDetail = new Model_DbTable_Roster_Stafflogindetail();
			$attRecord = new Model_DbTable_Roster_Attnrecord();
				
			$arrFileNames = array();
			$exportFolder = getcwd()."/export/timesheet/";
			$zipFolder =  getcwd()."/export/timesheetzip/";
			
				
			$orgFileName = "TS_WHCH_".$dateBegin."-".$dateEnd.".txt";
				
			foreach($arrFileNameStr as $key => $value){
				if($value!=""){
					$fileName = $value.$orgFileName;
					$strFileHead = implode("\t",$arrFileHead);
					$fl = fopen($exportFolder.$fileName,"w");
					fputs($fl,$strFileHead."\r\n");
					fclose($fl);
						
				}
			}
				
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			foreach($cashStaff as $k2 => $v2){
				foreach($arrDate as $dateCheck){
						
						
					//$v = arrShift;
					$arrShift = $tSheet->listShiftByDateId($v2, $dateCheck, $dateCheck);
					//var_dump($arrShift);
					//get 6 pm that date
					$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
					foreach($arrShift as $k => $v){
						$errorFlag = 0;
						$staffID = $v["id_staff"];
						$shopHead = $v["shop_head"];
						$attLine = $attRecord->getFirstOnLastOffDuty($staffID, $dateCheck,Model_EncryptHelper::sslPassword($shopHead));
			
						$stLine = $stDetail->getDetail($staffID);
						$stInfoLine = $stInfo->getStaffinfo($staffID);
							
							
						if(!$stLine){
								
							if(!$stLine){
								$errorFlag = 1;
								$fullName = Model_EncryptHelper::getSslPassword($stLine["n"]);
									
								echo "ERROR-".$staffID."-".$stLine["ni"]."-".$fullName."<br />";
									
							}
							else{
									
								$errorFlag = 2;
									
								echo "Warehouse Staff Just Ignore This Line<br />";
									
							}
						}
							
						else{
								
							//staff Name
							$statusLine = $dateCheck.", for ".$stLine["ni"]."-".Model_EncryptHelper::getSslPassword($stLine["n"]);
								
							$fullName = explode(" ",Model_EncryptHelper::getSslPassword($stLine["n"]));
								
							$errorPerson = true;
								
							$firstName = $fullName[0];
							$lastName = $fullName[1];
							$cardID = ucwords(Model_EncryptHelper::getSslPassword($stLine["n"]));
							$recordID = "000";
							$activeStaff = -1;
							$idPackage = 5;
								
							if($stInfoLine){
									
								$firstName = $stInfoLine["first_name"];
								$lastName = $stInfoLine["last_name"];
								$cardID = $stInfoLine["id_card"];
									
								$activeStaff = $stInfoLine["active_staff"];
								$idPackage = $stInfoLine["id_package"];
									
									
								$recordID =  $stInfoLine["id_record"];
									
								if($idPackage == 2 || $idPackage == 5){
									$recordID =  $stInfoLine["id_record_cash"];
								}
									
									
							}
			
								
								
							$strDate = date("j/m/Y",strtotime($dateCheck));
								
							$firstBreak = 0;
							$breakTime = 1800;
							$firstBreakStr = "";
							if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
								$breakTime  = 0;
							}
							if((($v["confirm_shift_end"]-$v["confirm_shift_begin"])<18000) && ($v["break_time"] == 0 ||$v["break_time"]== null )){
									
								$breakTime = 0;
							}
								
							if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 32400){
									
								$firstBreak = 1800;
								$firstBreakStr = "Over 9Hour , Will Dedute Another 0.5 Hr <br />";
								//"FIRST BREAK".$firstBreak."<br />";
							}
							$manShiftBegin = $v["confirm_shift_begin"];
							$manShiftEnd = $v["confirm_shift_end"];
								
							$statusLine .= ",Manager Allocate Time is :".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd);
							$statusLine .= ",Staff Self Fill Time is :".date("H:i",$v["shift_begin"])."-".date("H:i",$v["shift_end"]);
							$statusLine .= ",Break Time is:".$breakTime/60;
							
							$actBegin = "";
							$actEnd = "";
							if($attLine[0]){
								$actBegin = $attLine[0] - 3600*3;
							}
							if($attLine[1]){
								$actEnd = $attLine[1]- 3600*3;
							}
							
							$statusLine .=",Staff Actually Come On :";
							$statusLine .= ($actBegin=="")?"[NO COME RECORD]":date("H:i",$actBegin);
							$statusLine .=" and Actally Leave On :";
							$statusLine .=($actEnd=="")?"[NO LEAVE RECORD]":date("H:i",$actEnd);
							$statusLine .=", Total Hrs Allocated is: ".($manShiftEnd-$manShiftBegin)/3600;
							$statusLine .=", After Break ,It change to:".($manShiftEnd-$manShiftBegin-$breakTime)/3600;
								
							$afterFix = "[S]".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd)."[B]".round($breakTime/3600,2);
								
							if($manShiftBegin!= null && $actBegin!="" && ( $actBegin > ($manShiftBegin + 300))){
									
								$manShiftBegin = $actBegin;
								$afterFix.="[LA]".round(($actBegin-$v["confirm_shift_begin"])/3600,2);
								$statusLine .="Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".round(($actBegin-$v["confirm_shift_begin"])/60,0)." mins";
									
							}
								
							if($actEnd!="" && $manShiftEnd!= null && ( ($actEnd + 300) < $manShiftEnd) ){
									
								$manShiftEnd = $actEnd;
								$afterFix .="[EL]".round(($v["confirm_shift_end"]-$actEnd)/3600,2);
								$statusLine .= ", Leave Early on  ".date("H:i",$actEnd)." so I deduct".round(($v["confirm_shift_end"]-$actEnd)/60,2)." mins";
							}
								
							$shiftBegin = $manShiftBegin;
							$shiftEnd = $manShiftEnd - $breakTime;
								
							if($actBegin=="" || $actEnd == "" || $v["confirm_shift_begin"] == null || $v["confirm_shift_end"] = null){
									
								$shiftBegin = 0;
								$shiftEnd = 0;
							}
								
								
							$adjustTime = ($v["admin_adjust"]===null)?0:$v["admin_adjust"];
							//final adjust
							$statusLine .= $firstBreakStr;
							echo $statusLine."<br />";
			
							//public holiday
							if(in_array($dateCheck,$arrPublicHoliday)){
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
									
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff >-1 ){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								}
									
							}
							elseif(date("N",strtotime($dateCheck)) == 7){
									
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff >-1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								}
								if($hours > 0 && $activeStaff== -1){
									if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
										$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
									}
										
									$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
			
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
										
								}
									
									
									
							}
							elseif(date("N",strtotime($dateCheck)) == 6){
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
								if($hours > 0 && $activeStaff > -1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
								}
								if($hours > 0 && $activeStaff==-1){
									if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
										$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
									}
										
									$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
			
									$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
								}
							}
							else{
								//1-5
									
								if($v["shop_head"] == "ADPC" || $v["shop_head"] == "CLPC" || $v["shop_head"] == "WLIC" || $v["shop_head"] == "CLIC" ){
									$date6Pm = date("U",strtotime($dateCheck." 18:30:00"));
								}
								else{
			
									$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
								}
									
									
								if($shiftBegin < $date6Pm && $shiftEnd <= $date6Pm){
									// total Normal hour
									//echo "FIRST BREAK".$firstBreak."<br />";
									$hours = round(($shiftEnd-$shiftBegin + $adjustTime -$firstBreak )/3600,2);
									$strBegin = date("H:i",$shiftBegin);
									$strEnd = date("H:i",$shiftEnd);
									$strStartStopTime = $strBegin."-".$strEnd;
			
									//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
									if($hours > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
											
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
											
									}
									if($hours > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
											
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
											
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
								}
								if($shiftBegin >=$date6Pm){
										
									$hours = round(($shiftEnd-$shiftBegin + $adjustTime )/3600,2);
									$strBegin = date("H:i",$shiftBegin);
									$strEnd = date("H:i",$shiftEnd);
									$strStartStopTime = $strBegin."-".$strEnd;
			
									//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
									if($hours > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
											
									}
									if($hours > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
											
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
											
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
									//total 6 pm
										
								}
								if($shiftBegin< $date6Pm && $shiftEnd > $date6Pm){
									//before and after
									$hoursNormal = round(($date6Pm-$shiftBegin-$firstBreak)/3600,2);
									$strBegin = date("H:i",$shiftBegin);
									$strEnd = date("H:i",$shiftEnd);
									$strStartStopTime = $strBegin."-".$strEnd;
			
									//$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Date","Units","Emp. Card ID","Emp. Record ID");
									if($hoursNormal > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
											
									}
									if($hoursNormal > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
											
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
											
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
									$hoursExt = round(($shiftEnd-$date6Pm)/3600,2);
									echo "Ext Hour is".$hoursExt."|";
			
									if($hoursExt > 0 && $activeStaff >-1){
										$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
											
									}
									if($hoursExt > 0 && $activeStaff == -1){
										if(!file_exists($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName)){
											$this->writeArrHeadToFile($staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName);
										}
											
										$fl = fopen($exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName,"a");
										$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
										//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
										$strTmp = implode("\t",$arrTmp);
										fputs($fl,$strTmp."\r\n");
										fclose($fl);
										$arrFileNames[] = $exportFolder.$staffID."_".$lastName."_".str_replace(" ","_",$firstName)."_MISS_MYOB_".$orgFileName;
									}
								}
									
							}
			
						}//end else
					}
				}
			}
			// sort name s
			
			$arrFileNames = array_unique($arrFileNames,SORT_STRING);
				
			$fileHandler = new Model_Fileshandler();
			$zipFileName = "MYOB_TS_WHCH_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
			$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);
			
			$this->view->link = "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
			$this->renderScript("/rosteraudit/payroll-wizard-complete.phtml");
				*/
			
			
			
		}
	}
	
	/**
	 *  This function is for summary rate/type/leave change 
	 *  holiday in current payroll cycle 
	 */
	public function payrollWizardHqChangeSummaryAction(){
		$dateEnd = Model_DatetimeHelper::dateToday();
		$dateBegin = Model_DatetimeHelper::adjustMonths("sub",Model_DatetimeHelper::getLastWeekMonday(),12);
		
		$dateStart = $this->_getParam("date_begin");
		$dateFinish = $this->_getParam("date_end");
		
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stfDetail = new Model_DbTable_Roster_Stafflogindetail();
		$stfLogin = new Model_DbTable_Roster_Attnrecord();
		$allStaff = $stfDetail->listWhStaff();
		$leave = new Model_Hr_Staffleave();
		
		$nonLoginList = array();
		$annleaveList = array();
		foreach($allStaff as $k => $v){
			if($v['id'] != 431 && $v['id'] != 410){
		
				$loginCheck = $stfLogin->listRecordByStaffId($v['id'], $dateStart, $dateFinish);
		
				if(!$loginCheck){
					$nonLoginList[] = $v;
				}
				$stfLeave = $leave->getApproveLeaveByIdPeriod($v['id'], $dateStart, $dateFinish);
				if($stfLeave){
					$annleaveList[$v['id']] = $stfLeave;
				}
			}
		}
		
		$typeList = $stInfo->listChangesWhUnhandle($dateBegin, $dateEnd,"type");
		$rateList = $stInfo->listChangesWhUnhandle($dateBegin, $dateEnd,"rate");
		$leaveList =  $stInfo->listChangesWhUnhandle($dateBegin, $dateEnd,"leave");
		
		$this->view->nonLoginList = $nonLoginList;
		$this->view->typeList = $typeList;
		$this->view->rateList = $rateList;
		$this->view->leaveList = $leaveList;
		$this->view->dateStart = $dateStart;
		$this->view->dateEnd = $dateFinish;
		$this->view->annLeaveList = $annleaveList;

		
		if(isset($_POST['next'])){
			$stInfo = new Model_DbTable_Roster_Staffinfo();
			$changeTypeList = array();
			$changeRateList = array();
			$leaveList = array();
			if(!empty($_POST['checksign1'])){
				foreach($_POST['checksign1'] as $k1 => $v1){
					$idStaff = $_POST['id_staff1'][$k1];
					$stInfo->updateChanges($idStaff, "type");
				}
			}
			if(!empty($_POST['checksign2'])){
				foreach($_POST['checksign2'] as $k2 => $v2){
					
					$idStaff = $_POST['id_staff2'][$k2];
					$stInfo->updateChanges($idStaff, "rate");
				}
			}
			if(!empty($_POST['checksign3'])){
				foreach($_POST['checksign3'] as $k3 => $v3){
					$idStaff = $_POST['id_staff3'][$k3];
					$stInfo->updateChanges($idStaff, "leave");
				}
			}
			
			$url = "/rosteraudit/payroll-wizard-wh-select/dateBegin/".$dateStart."/dateEnd/".$dateFinish;
			$this->_redirect($url);
		}
	}
	
	/**
	 * Handle all opening case
	 */
	public function payrollWizardOpeningCaseAction(){
		$attCase = new Model_DbTable_Roster_Attncase();
		$acRecord = new Model_DbTable_Roster_Attcaserecord();
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd= $this->_getParam("date_end");
		$dateToday = Model_DatetimeHelper::dateToday('');
		$date2MonthAgo = Model_DatetimeHelper::adjustDays('sub', $dateToday, 60);
		
		$openCase = $attCase->listUndecidedCase();
		$waitCase = $attCase->listWillpayCase();
		$rejectCase = $attCase->listRejectCasebyDate($date2MonthAgo, $dateToday);
		$paidCase 	= $attCase->listPaidCasebyDate($date2MonthAgo, $dateToday);
		
		$nextCheck = $this->_getParam("next");
		if($nextCheck == 'yes'){
			$check = true;
			$this->view->nextCheck = $check;
		}
		
		$this->view->openCase = $openCase;
		$this->view->waitCase = $waitCase;
		$this->view->rejectCase = $rejectCase;
		$this->view->paidCase = $paidCase;
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		if(isset($_POST['change_date'])){
			$dateStart 	= $_POST['begin_date'];
			$dateFinish = $_POST['finish_date'];
			$rejectCase = $attCase->listRejectCasebyDate($dateStart, $dateFinish);
			$this->view->rejectCase = $rejectCase;
			
		}
		if(isset($_POST['change_date2'])){
			$dateStart 	= $_POST['begin_date2'];
			$dateFinish = $_POST['finish_date2'];
			$paidCase 	= $attCase->listPaidCasebyDate($dateStart, $dateFinish);
			$this->view->paidCase = $paidCase;
		}
		
		
	}
	
	/**
	 * This function is for export file for MYOB
	 * Include full/bonus/time-sheet/new staff
	 */
	public function payrollWizardExportSheetAction(){
		$dateBegin = $this->_getParam("date_begin");
		$dateEnd= $this->_getParam("date_end");
		$this->view->dateStart = $dateBegin;
		$this->view->dateEnd = $dateEnd;
		$payrollCycle = unserialize(PAYROLL_CYCLE_SELECT);
		$payrollDetail = new Model_DbTable_Payrolldetail();
		$currentCycle = $payrollDetail->getlastPayrollCycle();
		$attCase = new Model_DbTable_Roster_Attncase();
		$missArray = array();
		
		$intDateToday = Model_DatetimeHelper::tranferToInt(Model_DatetimeHelper::getThisWeekMonday());
		$ts = new Model_DbTable_Roster_Timesheet();
		$ts->updateLock($intDateToday);
		
		
		date_default_timezone_set('Australia/Melbourne');
		$TodayDate = date('Y-m-d', time());
		
		$arrPublicHoliday = unserialize(VIC_PUBLIC_HOLIDAY);
		$arrPublicHolidaySa = unserialize(SA_PUBLIC_HOLIDAY);
		$arrFileHead = array("Emp. Co./Last Name","Emp. First Name","Payroll Category","Note","Date","Units","Start/Stop Time","Emp. Card ID","Emp. Record ID");
		
		$arrPayment = array(
				0 =>array(),
				1 =>array("a"=>"Base Salary Package","b"=>"Base Salary Package","c"=>"Base Salary Package","d"=>"Base Salary Package","e"=>"Base Salary Package"),
				2 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				3 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				4 =>array("a"=>"Base Hourly","b"=>"Saturday Pay","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				5 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				6 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly"),
				7 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Saturday Pay","d"=>"Sunday Pay","e"=>"Public Holiday Pay"),
				8 =>array("a"=>"Base Hourly","b"=>"Base Hourly","c"=>"Base Hourly","d"=>"Base Hourly","e"=>"Base Hourly")
		);
		$arrFileNameStr = unserialize(PAY_FILE_TYPE);
		
		$tSheet = new Model_DbTable_Roster_Timesheet();
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$attRecord = new Model_DbTable_Roster_Attnrecord();
		
		$arrFileNames = array();
		$exportFolder = getcwd()."/export/timesheet/";
		$zipFolder =  getcwd()."/export/timesheetzip/";
		
		if(isset($_POST['button'])){
			$dateBegin = $_POST["date_begin"];
			$dateEnd = $_POST["date_end"];
		
				
			$orgFileName = "TS_".$dateBegin."-".$dateEnd.".txt";
			$fullFileName = "FULL_".$dateBegin."-".$dateEnd.".txt";
			$bonusFileName = "BONUS_".$dateBegin."-".$dateEnd.".txt";
			$allowFileName = "ALLOWANCE_".$dateBegin."-".$dateEnd.".txt";
				
			foreach($arrFileNameStr as $key => $value){
				if($value!=""){
					$fileName = $value.$orgFileName;
					
					$strFileHead = implode("\t",$arrFileHead);
					$fl = fopen($exportFolder.$fileName,"w");
					
					fputs($fl,$strFileHead."\r\n");
					
					fclose($fl);
					
				}
			}
				
			$arrDate = Model_DatetimeHelper::createDateArray($dateBegin, $dateEnd);
			foreach($arrDate as $dateCheck){
				$tmpfinalShift = array();
				$lastShift = array();
				
				
				$arrShift = $tSheet->listShiftByDate($dateCheck, $dateCheck);
				foreach ($arrShift as $k => $v){
					$shiftHour = ($v['confirm_shift_end'] - $v['confirm_shift_begin'])/3600;
					if($shiftHour != 0){
						$tmpfinalShift[$v['id_staff']][$v['shop_head']][] = $v;
					}
				}

				foreach ($tmpfinalShift as $sId => $shift){
					foreach ($shift as $sName => $sRoster){
						if(count($sRoster) > 1){
							$hr = ($sRoster[0]['confirm_shift_end'] - $sRoster[0]['confirm_shift_begin'])/3600;
							$lastShift[$sId][$sName] = $sRoster[0];
							foreach ($sRoster as $k => $v){
								$tmpHr = ($v['confirm_shift_end'] - $v['confirm_shift_begin'])/3600;
								if($tmpHr < $hr){
									$hr = $tmpHr;
									$lastShift[$sId][$sName] = $v;
								}
							}
						}else{
							$lastShift[$sId][$sName] = $sRoster[0];
						}
					}
				}
				//d($lastShift);
				//var_dump($arrShift);
				//get 6 pm that date
				$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
			
		
			foreach ($lastShift as $k2 => $v2){
				foreach($v2 as $k => $v){
					$errorFlag = 0;
						
					$staffID = $v['id_staff'];
					$shopHead = $v["shop_head"];
					$attLine = $attRecord->getFirstOnLastOffDuty($staffID, $dateCheck,Model_EncryptHelper::sslPassword($shopHead));
					$stLine = $stDetail->getDetail($staffID);
					$stInfoLine = $stInfo->getStaffinfo($staffID);
						
					$needWarehouse = false;

					if($stInfoLine['position_status']==8 || $stInfoLine['is_wh'] == 1 || $stInfoLine['is_wh'] == 2){
						$needWarehouse = true;	
					}

					if(!$stLine || $needWarehouse){
		
						if(!$stLine){
							$errorFlag = 1;
							$fullName = Model_EncryptHelper::getSslPassword($stLine["n"]);
		
							echo "ERROR-".$staffID."-".$stLine["ni"]."-".$fullName."<br />";
		
						}
						else{
		
							$errorFlag = 2;
								
							//echo "Warehouse Staff Just Ignore This Line<br />";
								
						}
					}
						
					else{

						//staff Name
						$statusLine = $dateCheck.", for ".$stLine["ni"]."-".Model_EncryptHelper::getSslPassword($stLine["n"]);
		
						$fullName = explode(" ",Model_EncryptHelper::getSslPassword($stLine["n"]));
		
						$errorPerson = true;
		
						$firstName = $fullName[0];
						$lastName = $fullName[1];
						$cardID = ucwords(Model_EncryptHelper::getSslPassword($stLine["n"]));
						$recordID = "000";
						$activeStaff = -1;
						$idPackage = 5;
		
						
						
						
						if($stInfoLine){
								
							$firstName = $stInfoLine["first_name"];
							$lastName = $stInfoLine["last_name"];
							$cardID = $stInfoLine["id_card"];
								
							$activeStaff = $stInfoLine["active_staff"];
							if($stInfoLine["id_package"]){
								$idPackage = $stInfoLine["id_package"];
							}else{
								$idPackage = 5;
							}
							
								
							$recordID =  $stInfoLine["id_record"];
								
							if($idPackage == 2 || $idPackage == 5){
								$recordID =  $stInfoLine["id_record_cash"];
							}
								
						}
						// Export leave time sheet
						/*
						if($v['holiday_check'] == 1){
							$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
							$strDate = date("j/m/Y",strtotime($dateCheck));
							$hours = round(($v['shift_end'] - $v['shift_begin'])/3600,2);
							if($hours > 8){
								$hours = 8;
							}
							$strStartStopTime = date("H:i",$v['shift_begin'])."-".date("H:i",$v['shift_end']);
							$afterFix = "[S]".date("H:i",$v['shift_begin'])."-".date("H:i",$v['shift_end'])."[B]0";
							$arrTmp = array($lastName,$firstName,'Holiday Pay',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
						
							$strTmp = implode("\t",$arrTmp);
							fputs($fl,$strTmp."\r\n");
							fclose($fl);
							$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
						}else{
						*/
		
		
						$strDate = date("j/m/Y",strtotime($dateCheck));
		
						$firstBreak = 0;
						$breakTime = 1800;
						$firstBreakStr = "";
						if($v["break_time"]===(int)0 and $v["break_time"]!== null ){
							//$breakTime  = 0;
						}
						
						if((($v["confirm_shift_end"]-$v["confirm_shift_begin"])<18000) && ($v["break_time"] == 0 ||$v["break_time"]== null )){
								
							$breakTime = 0;
						}
						if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 18000){
							if($breakTime < 1800){
								$breakTime = 1800;
								$firstBreakStr = "Over 5 Hour , Will Dedute By 0.5 Hr <br />";
							}
							
							if($v['break_time'] != 0){
								if($v['break_time'] <= 1800){
									$breakTime = 1800;
									$firstBreakStr = "Over 5 Hour , Will Dedute By 0.5 Hr <br />";
								}else{
									$breakTime = $v['break_time'];
									$firstBreakStr = "Over 5 Hour , Will Dedute ".($breakTime/60)." Hr <br />";
								}	
							}
							//"FIRST BREAK".$firstBreak."<br />";
						}
						if(($v["confirm_shift_end"]-$v["confirm_shift_begin"]) >= 32400){
							
							if($v['break_time'] >=  3600){
								$breakTime = 1800;
								$firstBreak = $v['break_time'] - $breakTime;
								$firstBreakStr = "Over 9Hour , Arrange  another ".($firstBreak/60)." Hr break <br />";
							}else{
								$firstBreak = 1800;
								$firstBreakStr = "Over 9Hour , Will Dedute Another 0.5 Hr <br />";
							}
							//"FIRST BREAK".$firstBreak."<br />";
						}
						$manShiftBegin = $v["confirm_shift_begin"];
						$manShiftEnd = $v["confirm_shift_end"];
		
						$statusLine .= ",Manager Allocate Time is :".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd);
						$statusLine .= ",Staff Self Fill Time is :".date("H:i",$v["shift_begin"])."-".date("H:i",$v["shift_end"]);
						$statusLine .= ",Break Time is:".$breakTime/60;
		
						$actBegin = $attLine[0];
						$actEnd = $attLine[1];
		
						$statusLine .=",Staff Actually Come On :";
						$statusLine .= ($actBegin=="")?"[NO COME RECORD]":date("H:i",$actBegin);
						$statusLine .=" and Actally Leave On :";
						$statusLine .=($actEnd=="")?"[NO LEAVE RECORD]":date("H:i",$actEnd);
						$statusLine .=", Total Hrs Allocated is: ".($manShiftEnd-$manShiftBegin)/3600;
						$statusLine .=", After Break ,It change to:".($manShiftEnd-$manShiftBegin-$breakTime)/3600;
		
						$afterFix = "[S]".date("H:i",$manShiftBegin)."-".date("H:i",$manShiftEnd)."[B]".round($breakTime/3600,2);
		
						if($manShiftBegin!= null && $actBegin!="" && ( $actBegin > ($manShiftBegin + 300))){
		
							$manShiftBegin = $actBegin;
							$afterFix.="[LA]".round(($actBegin-$v["confirm_shift_begin"])/3600,2);
							$statusLine .="Since come time is on ".date("H:i",$actBegin).", which is LATE, so I deduct ".round(($actBegin-$v["confirm_shift_begin"])/60,0)." mins";
			
								
						}
		
						if($actEnd!="" && $manShiftEnd!= null && ( ($actEnd + 300) < $manShiftEnd) ){
								
							$manShiftEnd = $actEnd;
							$afterFix .="[EL]".round(($v["confirm_shift_end"]-$actEnd)/3600,2);
							$statusLine .= ", Leave Early on  ".date("H:i",$actEnd)." so I deduct".round(($v["confirm_shift_end"]-$actEnd)/60,2)." mins";
						}
		
						$shiftBegin = $manShiftBegin;
						$shiftEnd = $manShiftEnd - $breakTime;
		
						if($actBegin=="" || $actEnd == "" || $v["confirm_shift_begin"] == null || $v["confirm_shift_end"] = null){
								
							$shiftBegin = 0;
							$shiftEnd = 0;
						}
		
		
						$adjustTime = ($v["admin_adjust"]===null)?0:$v["admin_adjust"];
						//final adjust
						$statusLine .= $firstBreakStr;
						//echo $statusLine."<br />";
							
						//public holiday
						if(in_array($dateCheck,$arrPublicHoliday)){
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
		
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
		
							
							if($hours > 0 && $activeStaff >-1 ){
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["e"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								
								$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
								fputs($f2,$strTmp."\r\n");
								fclose($f2);
								
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
							}
							if($hours > 0 && $activeStaff== -1){
								$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["e"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
							
							}
								
						}
						elseif(date("N",strtotime($dateCheck)) == 7){//Sunday Pay
								
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
								
							
							if($hours > 0 && $activeStaff >-1){
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["d"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								
								$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
								fputs($f2,$strTmp."\r\n");
								fclose($f2);
								
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
							}
							if($hours > 0 && $activeStaff== -1){
								$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["d"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
	
							}
								
								
								
						}
						elseif(date("N",strtotime($dateCheck)) == 6){//Saturday Pay
							$hours = round(($shiftEnd-$shiftBegin + $adjustTime - $firstBreak )/3600,2);
							$strBegin = date("H:i",$shiftBegin);
							$strEnd = date("H:i",$shiftEnd);
							$strStartStopTime = $strBegin."-".$strEnd;
								
							
							if($hours > 0 && $activeStaff > -1){
								
								$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
								$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
								//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["c"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
								$strTmp = implode("\t",$arrTmp);
								fputs($fl,$strTmp."\r\n");
								fclose($fl);
								
								$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
								fputs($f2,$strTmp."\r\n");
								fclose($f2);
								
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
								$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
							}
							if($hours > 0 && $activeStaff==-1){
						
								$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["c"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
							
							}
						}
						else{
							//1-5
		
							if($v["shop_head"] == "ADPC" || $v["shop_head"] == "CLPC" || $v["shop_head"] == "WLIC" || $v["shop_head"] == "CLIC" ){
								$date6Pm = date("U",strtotime($dateCheck." 18:30:00"));
							}
							else{
									
								$date6Pm = date("U",strtotime($dateCheck." 18:00:00"));
							}
								
		
							if($shiftBegin < $date6Pm && $shiftEnd <= $date6Pm){
								// total Normal hour
								//echo "FIRST BREAK".$firstBreak."<br />";
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime -$firstBreak )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								
								if($hours > 0 && $activeStaff >-1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									
									$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
									fputs($f2,$strTmp."\r\n");
									fclose($f2);
									
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
		
								}
								if($hours > 0 && $activeStaff == -1){
								
									$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["a"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									
								}
							}
							if($shiftBegin >=$date6Pm){ //after 6 Pay
		
								$hours = round(($shiftEnd-$shiftBegin + $adjustTime )/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								
								if($hours > 0 && $activeStaff >-1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									
									$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
									fputs($f2,$strTmp."\r\n");
									fclose($f2);
									
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
		
								}
								if($hours > 0 && $activeStaff == -1){
									
									$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["b"],'Time Sheet',$strDate,$hours,$strStartStopTime.$afterFix,$cardID,$recordID);
									
								}
								//total 6 pm
		
							}
							if($shiftBegin< $date6Pm && $shiftEnd > $date6Pm){
								//before and after
								$hoursNormal = round(($date6Pm-$shiftBegin-$firstBreak)/3600,2);
								$strBegin = date("H:i",$shiftBegin);
								$strEnd = date("H:i",$shiftEnd);
								$strStartStopTime = $strBegin."-".$strEnd;
									
								
								if($hoursNormal > 0 && $activeStaff >-1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],'Time Sheet',$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
									//$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["a"],$strDate,$hours,$strStartStopTime.$afterFix,$recordID);
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									
									$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
									fputs($f2,$strTmp."\r\n");
									fclose($f2);
										
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
		
								}
								if($hoursNormal > 0 && $activeStaff == -1){
									
									$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["a"],'Time Sheet',$strDate,$hoursNormal,$strStartStopTime.$afterFix,$cardID,$recordID);
									
								}
								$hoursExt = round(($shiftEnd-$date6Pm)/3600,2);
			
									
								
								if($hoursExt > 0 && $activeStaff >-1){
									$fl = fopen($exportFolder.$arrFileNameStr[$idPackage].$orgFileName,"a");
									$arrTmp = array($lastName,$firstName,$arrPayment[$idPackage]["b"],'Time Sheet',$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
									
									$strTmp = implode("\t",$arrTmp);
									fputs($fl,$strTmp."\r\n");
									fclose($fl);
									
									$f2 = fopen($exportFolder.$arrFileNameStr[$idPackage].$fullFileName,"a");
									fputs($f2,$strTmp."\r\n");
									fclose($f2);
									
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$fullFileName;
									$arrFileNames[] = $exportFolder.$arrFileNameStr[$idPackage].$orgFileName;
		
								}
								if($hoursExt > 0 && $activeStaff == -1){
									
									$missArray[$staffID][] = array($lastName,$firstName,$arrPayment[$idPackage]["b"],'Time Sheet',$strDate,$hoursExt,$strStartStopTime.$afterFix,$cardID,$recordID);
									
								}
							}
								
						}
						//} // end of holiday check 
					}//end else
				}
			}
			}
			
			
			$shortCase = $attCase->listPaidCasebyDate($dateBegin, $dateEnd);
			foreach($shortCase as $k3 => $v3){
				$stfP = $stInfo->getStaffinfo($v3['id_staff']);
				$appDate = date("j/m/Y",strtotime($v3['shift_date']));
			  if($stfP['active_staff'] > -1){
				
				if($v3['hour_allocate_normal'] != 0){
					$fl = fopen($exportFolder.$arrFileNameStr[$stfP['id_package']].$fullFileName,"a");
					if($stfP['id_package'] == 2 || $stfP['id_package'] == 5){
					
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["a"],'Short Pay',$appDate,$v3['hour_allocate_normal'],'0000-00-00',$stfP['id_card'],$stfP['id_record_cash']);
					}else{
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["a"],'Short Pay',$appDate,$v3['hour_allocate_normal'],'0000-00-00',$stfP['id_card'],$stfP['id_record']);
					}
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
				}
				if($v3['hour_allocate_6pm'] != 0){
					$fl = fopen($exportFolder.$arrFileNameStr[$stfP['id_package']].$fullFileName,"a");
					if($stfP['id_package'] == 2 || $stfP['id_package'] == 5){
							
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["b"],'Short Pay',$appDate,$v3['hour_allocate_6pm'],'0000-00-00',$stfP['id_card'],$stfP['id_record_cash']);
					}else{
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["b"],'Short Pay',$appDate,$v3['hour_allocate_6pm'],'0000-00-00',$stfP['id_card'],$stfP['id_record']);
					}
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
				}
				if($v3['hour_allocate_sat'] != 0){
					$fl = fopen($exportFolder.$arrFileNameStr[$stfP['id_package']].$fullFileName,"a");
					if($stfP['id_package'] == 2 || $stfP['id_package'] == 5){
							
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["c"],'Short Pay',$appDate,$v3['hour_allocate_sat'],'0000-00-00',$stfP['id_card'],$stfP['id_record_cash']);
					}else{
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["c"],'Short Pay',$appDate,$v3['hour_allocate_sat'],'0000-00-00',$stfP['id_card'],$stfP['id_record']);
					}
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
				}
				if($v3['hour_allocate_sun'] != 0){
					$fl = fopen($exportFolder.$arrFileNameStr[$stfP['id_package']].$fullFileName,"a");
					if($stfP['id_package'] == 2 || $stfP['id_package'] == 5){
							
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["d"],'Short Pay',$appDate,$v3['hour_allocate_sun'],'0000-00-00',$stfP['id_card'],$stfP['id_record_cash']);
					}else{
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["d"],'Short Pay',$appDate,$v3['hour_allocate_sun'],'0000-00-00',$stfP['id_card'],$stfP['id_record']);
					}
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
				}
				if($v3['hour_allocate_pholiday'] != 0){
					$fl = fopen($exportFolder.$arrFileNameStr[$stfP['id_package']].$fullFileName,"a");
					if($stfP['id_package'] == 2 || $stfP['id_package'] == 5){
							
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["e"],'Short Pay',$appDate,$v3['hour_allocate_pholiday'],'0000-00-00',$stfP['id_card'],$stfP['id_record_cash']);
					}else{
						$arrTmp = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["e"],'Short Pay',$appDate,$v3['hour_allocate_pholiday'],'0000-00-00',$stfP['id_card'],$stfP['id_record']);
					}
					$strTmp = implode("\t",$arrTmp);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
				}
			  }else{
			  		$appDate = date("j/m/Y",strtotime($v3['shift_date']));
			  		if($stfP['id_package'] == 2 || $stfP['id_package'] == 5){
			  			$missArray[$stfP['id_staff']][] = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["a"],'Short Pay',$appDate,$v3['hour_allocate_normal'],'0000-00-00',$stfP['id_card'],$stfP['id_record_cash']);
			  		}else{
			  			$missArray[$stfP['id_staff']][] = array($stfP['last_name'],$stfP['first_name'],$arrPayment[$stfP['id_package']]["a"],'Short Pay',$appDate,$v3['hour_allocate_normal'],'0000-00-00',$stfP['id_card'],$stfP['id_record']);
			  		}
					
			  }
			}
			
			foreach ($missArray as $staff => $value){
				$missStf = $stInfo->getStaffinfo($staff);

				$this->writeArrHeadToFile($staff."_".$missStf['last_name']."_".$missStf['first_name']."_MISS_MYOB_".$orgFileName);
					
				foreach ($value as $k2 => $v2){
					$fl = fopen($exportFolder.$staff."_".$missStf['last_name']."_".$missStf['first_name']."_MISS_MYOB_".$orgFileName,"a");
					$strTmp = implode("\t",$v2);
					fputs($fl,$strTmp."\r\n");
					fclose($fl);
			
			
					$arrFileNames[] = $exportFolder.$staff."_".$missStf['last_name']."_".$missStf['first_name']."_MISS_MYOB_".$orgFileName;
				}
			
			}
			
			
			// sort name s
			$arrFileNames[] = $exportFolder."ACDF_".$bonusFileName;
			$arrFileNames[] = $exportFolder."BE_".$bonusFileName;
			$arrFileNames[] = $exportFolder."ACDF_".$allowFileName;
			$arrFileNames[] = $exportFolder."BE_".$allowFileName;
			
			$arrFileNames = array_unique($arrFileNames,SORT_STRING);

			
			$fileHandler = new Model_Fileshandler();
			$zipFileName = "MYOB_TS_".$dateBegin."_".$dateEnd."_".Model_DatetimeHelper::dateToday('').Model_DatetimeHelper::timeNow('').".zip";
			//Model_workinghourCheck::hourCheck($arrFileNames);
			$fileHandler->create_zip($arrFileNames,$zipFolder.$zipFileName);
				
			$this->view->newStaff = $missArray;
			$this->view->link = "Download File <a href=\"/export/timesheetzip/{$zipFileName}\" target=\"_blank\">HERE</a>";
			$this->renderScript("/rosteraudit/payroll-wizard-complete.phtml");
			
		}
		
		if(isset($_POST['confirm'])){
			$comment = $_POST['comment'];
			foreach($payrollCycle as $k => $v){
				if($dateBegin == $v[0] && $dateEnd == $v[1]){
					$cycleKey = $k;
				}
			}
			$dateToday = Model_DatetimeHelper::dateToday();
			$payrollDetail->addPayrollDetail($cycleKey, $dateToday,$comment);
			
			$this->view->cycleCheck = "done";
		}
		
	}
	/**
	 * For upload person file into person info
	 * @version
	 * @author Leo
	 * 
	 */
	public function updatePersonFileAction(){
		$std = base64_decode($this->_getParam('stid'));
		$fileType = new Model_DbTable_Roster_StaffFile();
		$staffDetail = new Model_DbTable_Roster_Staffinfo();
		$staffName = $staffDetail->getStaffinfo($std);
		$this->view->staffName = $staffName['first_name'].' '.$staffName['last_name'];
		
		$handler = opendir('./personFile');  
    	while (($filename = readdir($handler)) !== false) {
        	if ($filename != "." && $filename != "..") {  
                $files[] = $filename;  
          	 }  
       	}  
       	closedir($handler);
       	$validFile = array('Contract','Payslip','WarningLetter');
       	$mylist = array();
		
       	if($files != null){
			foreach($files as $k => $v){
				$myfile = explode("_",$v);
				if($myfile[0]== $std && in_array($myfile[1],$validFile)){
					$type = $fileType->getFileByType($myfile[1]);

					$mylist[$type['id_type']][] = $v;
				}
			}
			$this->view->filelist = $mylist;
       	}
		if(isset($_POST['upload'])){
			$fileName1 = "";
			$uploadFolder = getcwd()."/personFile/";
			
			$tmpName  = $_FILES["my_file"]["tmp_name"];
			$realName = $_FILES["my_file"]["name"];
			if(move_uploaded_file($tmpName,$uploadFolder.$realName)){
				$fileName1 = $realName;
			}else{
			$errorFlag = false;
			}
		
		}
	}
	
	/**
	 * this is the fuction to scan the etl paper 
	 * if scanned it means warehouse has receive the paper 
	 */
	public function scanEtlPaperAction(){
		
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$arrRes = array();
		
		
		if($_POST){
			
			$arrRes = unserialize(base64_decode($_POST['str_res']));
			$arrBc = explode('-', trim($_POST['barcode']));
		if($arrBc[0] >0 && $arrBc[1]){
			
			$stDetailLine  = $stDetail->getDetail($arrBc[0]);
			$fullName = Model_EncryptHelper::getSslPassword($stDetailLine['n']);
			$nickName = $stDetailLine['ni'];
			
		$log = new Model_Payroll_Etllog();
		$year = '';
		if(!isset($arrBc[2])){
		$year = '2014';
		}
		else{
			$year = '20'.$arrBc[2];
		}
		$timeNow = Model_DatetimeHelper::dateToday().' '.Model_DatetimeHelper::timeNow();
		
		//$log->addEtllog($arrBc[0], $arrBc[1], $year, $timeNow);
		$log->conditionUpdateLog($arrBc[0], $arrBc[1], $year, $timeNow);
		
		$arrRes[] = array($arrBc[0],$fullName,$nickName,$arrBc[1],$timeNow,$year);
		}
		}
		
		$this->view->arrRes = $arrRes;
		$this->view->strRes = base64_encode(serialize($arrRes));
	}
	
	/**
	 * this is show the list of payroll cycle and staff
	 * o means never create  x means not received v means paper come back already
	 */
	public function etlScanSummaryAction(){
		
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		$log = new Model_Payroll_Etllog();
		
		$stList = $log->listAllStaff();
		$cyList = $log->listAllCycle();
		
		//d($stList,$cyList);
		
		$arrRes = array();
		$arrStaff = array();
		
		foreach($stList as $idStaff){
			$stLine = $stDetail->getDetail($idStaff['id_staff']);
			
				$arrStaff[$idStaff['id_staff']] = $stLine['ni']." [".Model_EncryptHelper::getSslPassword($stLine['n'])."]";
			
			foreach($cyList as $cycle){
				
				$arrRes[$idStaff['id_staff']][$cycle['id_cycle']."-".$cycle['year']] = $log->logStatus($idStaff['id_staff'],$cycle['id_cycle'],$cycle['year']);
				
			}
			
			
		}
		
		$this->view->arrStaff = $arrStaff;
		$this->view->cyList = $cyList;
		$this->view->arrRes = $arrRes;
		
		
		
	}
	
	/**
	 * this is for manager the selection of super company in company info page 
	 */
	public function manageSuperCompanyAction(){
		
		$spc = new Model_Payroll_Supercomp();
		
		if($_POST){
			if(isset($_POST['btn_add'])){
				$spc->addSupercomp($_POST['sp_name']);
			}
			
			if(isset($_POST['btn_update'])){
				foreach($_POST['sp_name_update'] as $idSc => $nameSp){
					
					$spc->updateSupercomp($idSc, $nameSp);
				}
				
				echo "<h1>Company Name Updated!!</h1>";
			}
			
		}
		
		$this->view->spList = $spc->listAll();
		
		
	}
	
	/**
	 * only olga can update the person info page so it need to check passworkd
	 * other warehouse staff can only check the staff info page 
	 * 
	 */
	public function updatePersonInfoCheckPasswordAction(){
		
		date_default_timezone_set("Australia/Melbourne");
		
		$stid = $this->_getParam("stid");
		$this->view->stid = $stid;
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		if($_POST){
			$loginstaff = $stDetail->checkPasswordCorrect(Model_EncryptHelper::hashsha($_POST['password']));
			if($loginstaff['id'] == 165 || $loginstaff['id'] == 337 || $loginstaff['id'] == 431 || $loginstaff['id'] == 379){ // only olga accepted
				if($loginstaff['id'] == 165 || $loginstaff['id'] == 337  || $loginstaff['id'] == 379 || $loginstaff['id'] == 431){	
				setcookie("readonly","readonlyModify",time() + 600,"/rosteraudit/");
				}
				if($loginstaff['id'] == 286 ){
					
					setcookie("readonly","readonly",time() + 600,"/rosteraudit/");
				}
				
				$this->_redirect('/rosteraudit/update-person-info/stid/'.$stid);
				echo "Password Check Correct";
				//d($_COOKIE);
			}	
			
			
		}		
	}
	
	/**
	 * this funcion is to check the level 1- 4 document 
	 */
	public function checkUploadedDocumentAction(){
		
		$sid = $this->_getParam("id_staff");
		$idStaff = base64_decode($sid);
		$idAuditer = $this->_getParam("id_audit");
		
		if($idAuditer == ''){
			
			$idAuditer = 110;
		}
		
		$cPath = getcwd();
		$pFile = '/personFile/';
		$idDir = $idStaff.'/';
		
		$this->view->webPath = $pFile.$idDir;
		$arrFileList  = self::getDirectoryList($cPath.$pFile.$idDir);
		$this->view->idAuditer = $idAuditer;
		$this->view->idStaff = $idStaff;
		
		//d($arrFileList);
		
		$stInfo = new Model_DbTable_Roster_Staffinfo();
		$uploadLog = new Model_Hr_Uploadlog();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		//if post update the status and then affect to current status 
		// send email to assigned manager 
		
		if($_POST){
			
			$strlv1 = "Level 1 ID has Not been Uploaded <br/>";
			$strlv2 = "Level 2 ID has Not been Uploaded <br/>";
			$strlv3 = "Level 3 Documents has Not been Uploaded <br/>";
			
			$lv1 = 0;
			$lv2 = 0;
			$lv3 = 0;
			
			if(isset($_POST['rd_level1'])){
				
				$lv1 = ($_POST['rd_level1'] == "pass")?1:2;
				
				$strlv1 = ($_POST['rd_level1'] == "pass")?"Level 1 ID Has Passed The Audit.<br />":"Level 1 ID Did Not Pass,Please check the detail message below.<br />";
			}
			if(isset($_POST['rd_level2'])){
				$lv2 = ($_POST['rd_level2'] == "pass")?1:2;
				$strlv2 = ($_POST['rd_level2'] == "pass")?"Level 2 ID Has Passed The Audit.<br />":"Level 2 ID Did Not Pass,Please check the detail message below.<br />";
			
			}
			if(isset($_POST['rd_level3'])){
				$lv3 = ($_POST['rd_level3'] == "pass")?1:2;
				$strlv3 = ($_POST['rd_level3'] == "pass")?"Level 3 Documents Has Passed The Audit.<br />":"Level 3 Documents Did Not Pass,Please check the detail message below.<br />";
			
			}
			
			$stInfo->updateStatus($idStaff, $lv1, $lv2, $lv3);
			
			if($lv1 == 1 && $lv2 == 1 && lv3 == 1){
				// all passed 
				
				$stDetail->reActiveStaff($idStaff);
				$stInfo->activeStaff($idStaff);
				
			}
			
			//find the last manager id uplaoding 
			// if manager do not have email  send to will 
		
			$idManager = $uploadLog->getLastUploadManager($idStaff);
			
			$arrEmailMgr = unserialize(ARR_MANAGER_EMAIL);
			
			if(!$idManager || !isset($arrEmailMgr[$idManager]) ){$idManager = 165;}
			
			$emailAddr = $arrEmailMgr[$idManager];
			$email = new Model_Emailshandler();
			$mailbody = $strlv1.$strlv2.$strlv3.$_POST['message_to_manager']; // status 1 2 3
			//d($idManager,$emailAddr);
			
			$email->sendActionEmail($emailAddr,"Head Office just audited the file you uploaded, the details are as follow", $mailbody);
			
			echo "Email Sent To Manager";
			
			
		}
		
		
		$stPassStatus = $stInfo->getStaffDocStatus($idStaff);
		
		$dlFileName = $idStaff."_driver_license.jpg";
		$psFileName = $idStaff."_passport.jpg";
		$pvFileName = $idStaff."_passport_visa.jpg";
		$stCardFileName = $idStaff."_student_card.jpg";
		$mcCardFileName = $idStaff."_medicare_card.jpg";
		$cdCardFileName = $idStaff."_credit_card.jpg";
		$tfnFileName = $idStaff."_tfn_form.jpg";
		$preFixSignedDoc = "signed_doc_";
		$preFixOtherDoc = "oth_";
		
		
		$this->view->dlFileName = (file_exists($cPath.$pFile.$idDir.$dlFileName))?$dlFileName:'';
		$this->view->psFileName = (file_exists($cPath.$pFile.$idDir.$psFileName))?$psFileName:'';
		$this->view->pvFileName = (file_exists($cPath.$pFile.$idDir.$pvFileName))?$pvFileName:'';
		
		// if dl / ps / pv file is empty , then if it was pass set to null 
		$l1Status = NULL;
		if($this->view->dlFileName == '' && $this->view->psFileName == '' && $this->view->pvFileName == ''){
			if($stPassStatus[0] == -1 || $stPassStatus[0] == 1 ){
				$l1Status = 2;
			}		
		}
		else{
			$l1Status = $stPassStatus[0];
			
		}
		
		
		$this->view->stCardFileName = (file_exists($cPath.$pFile.$idDir.$stCardFileName))?$stCardFileName:'';
		$this->view->mcCardFileName = (file_exists($cPath.$pFile.$idDir.$mcCardFileName))?$mcCardFileName:'';
		$this->view->cdCardFileName = (file_exists($cPath.$pFile.$idDir.$cdCardFileName))?$cdCardFileName:'';
		$this->view->tfnFileName = (file_exists($cPath.$pFile.$idDir.$tfnFileName))?$tfnFileName:'';
		
		// if st / mc / cd file is empty , then if it was pass set to null
		$l2Status = NULL;
		
		if($this->view->stCardFileName == '' && $this->view->mcCardFileName == '' && $this->view->cdCardFileName == ''){
			if($stPassStatus[1] == -1 || $stPassStatus[1] == 1 ){
				$l2Status = 2;
			}
		}
		else{
			$l2Status = $stPassStatus[1];
				
		}
		
		
		$arrSdoc = array();
		$arrOdoc = array();
			
		foreach($arrFileList as $file){
		
			if(strpos($file,$preFixSignedDoc) !== false){
					
				$arrSdoc[] = $file;
			}
			if(strpos($file,$preFixOtherDoc) !== false){
		
				$filecomm = $uploadLog->findUploadComm($file,$idStaff);
					$fileVerify = $uploadLog->fileVerifyStatus($file, $idStaff);
					$arrOdoc[] = array($file,$filecomm,$fileVerify);
			}
		
		
		}
			
		$this->view->arrSdoc = $arrSdoc;
		// if $arrSdoc is empty then if it was pss set to null 
		$l3Status = NULL;
		if(empty($arrSdoc)){
			if($stPassStatus[2] == -1 || $stPassStatus[2] == 1 ){
				$l3Status = 2;
			}
		}
		else{
			$l3Status = $stPassStatus[2];
				
		} 
		$stInfo->updateStatus($idStaff, $l1Status, $l2Status, $l3Status);
		$this->view->arrOdoc = $arrOdoc;
		
		$this->view->l1Status = $l1Status;
		$this->view->l2Status = $l2Status;
		$this->view->l3Status = $l3Status;
		
		
		// check staff id 
		// find directory and list all files 
		
		// give choice 
		// after selection ,send email notice 
		// log into the log
		// mark  in staff info 
		
		
	}
	
	/**
	 * API function verify uploaded document and return to check document page 
	 */
	
	public function verifyUploadedFileAction(){
		
		$idStaff = $this->_getParam("id_staff");
		$idAuditer = $this->_getParam("id_audit");
		
		$fileName = $this->_getParam("file");
		$fileName = base64_decode($fileName);
		$uplog = new Model_Hr_Uploadlog();
		$uplog->verifyFile($fileName, $idStaff);
		
		$this->_redirect("/rosteraudit/check-uploaded-document/id_staff/".base64_encode($idStaff)."/id_audit/".$idAuditer);
			
	}
	
	/**
	 * API funcon to remove the uploaded document and return to check document page 
	 */
	public function removeUploadedFileAction(){
		
		$arrMgrEmail = unserialize(ARR_MANAGER_EMAIL);
		
		$idStaff = $this->_getParam("id_staff");
		$idAuditer = $this->_getParam("id_audit");
		
		$fileName = $this->_getParam("file");
		$fileName = base64_decode($fileName);
		
		$cPath = getcwd();
		$pFile = '/personFile/';
		$idDir = $idStaff.'/';
		$upLog = new Model_Hr_Uploadlog();
		$stDetail = new Model_DbTable_Roster_Stafflogindetail();
		
		$stName = $stDetail->getDetail($idStaff);
		
		if(!unlink($cPath.$pFile.$idDir.$fileName)){
			echo "Remove File Failed, Please Contact IT Immediatelly";
		}
		else{
			// find upload manger 
			$idManger = $upLog->getLastUploadManager($idStaff);
			
			$mail = new Model_Emailshandler();
			$mail->sendActionEmail($arrMgrEmail[$idManger],"File:".$fileName." Has been Removed in Staff File:".$stName['ni'],"You are the last Manager who handling the file , please have a check ");
			
			
			
			echo '';
			$this->_redirect("/rosteraudit/check-uploaded-document/id_staff/".base64_encode($idStaff)."/id_audit/".$idAuditer);
			echo "";
		}
			
	}
	
	/**
	 * private function to list all the file in the directory 
	 * @param unknown_type $directory
	 * @return multitype:string
	 */
	private static function getDirectoryList ($directory)
	{
	
		// create an array to hold directory list
		$results = array();
		
		if(file_exists($directory)){
		// create a handler for the directory
		$handler = opendir($directory);
	
		// open directory and walk through the filenames
		
		while ($file = readdir($handler)) {
	
			// if file isn't this directory or its parent, add it to the results
			if ($file != "." && $file != "..") {
				$results[] = $file;
			}
	
		}
		
		// tidy up: close the handler
		closedir($handler);
		}
		// done!
		return $results;
	
	}
	
}
?>